简体   繁体   English

如何在Javascript函数中编码HTML字符?

[英]How do I encode HTML characters within Javascript functions?

to all Javascript experts this question might be just basics. 对于所有Javascript专家来说,这个问题可能只是基础知识。 I'm using jQuery and I am working on a tooltip created with jQuery.flot. 我正在使用jQuery,并且正在使用jQuery.flot创建工具提示。

The following is a part of my javascript function within an html file and this is exactly what I need to have the tooltip div to be rendered correctly: 以下是html文件中我的javascript函数的一部分,而这正是我需要正确显示工具提示div的内容:

$('<div id="tooltip">' + contents + '</div>').css( {

Because the div is not shown I used Firebug to look for the reason and the line of code from above shows the special characters < and > encoded as html entities < and > as you can see here: 因为未显示div,所以我使用Firebug查找原因,并且上面的代码行显示了特殊字符<和>编码为html实体<和>,如您在此处看到的:

$('&lt;div id="tooltip"&gt;' + contents + '&lt;/div&gt;').css( {

I was searching several online sources for a solution and tried things like .replace(/lt;/g,'<') or .html().text() and it took me more than three hours but nothing was helpful. 我在几个在线资源中寻找解决方案,并尝试了诸如.replace(/ lt; / g,'<')或.html()。text()之类的事情,这花了我超过三个小时的时间,但没有任何帮助。

I works fine on localhost. 我在本地主机上工作正常。

Full Source Code: 完整的源代码:

<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.categories.js"></script>
<![CDATA[
  <script type="text/javascript">

    $(function () {
      var data = [ ]]>{e1Array}<![CDATA[ ];
      $.plot($("#placeholder1"), [ data ], {
        series: {
          bars: {
            show: true,
            barWidth: 1,
            align: "center"
          }
        },
        grid: {
          hoverable: true,
          clickable: true
        },
        xaxis: {
          mode: "categories",
          tickLength: 0
        },
        yaxis: {
          min: 0,
          max: 1,
          ticks: 0
        }
      } );
    });

    var previousPoint = null;
    $("#placeholder1").bind("plothover", function (event, pos, item) {
      if (item) {
        if (previousPoint != item.datapoint) {
          previousPoint = item.datapoint;
          $("#tooltip1").remove();
          showTooltip(item.pageX, item.screenY, item.series.data[item.dataIndex][0] + ': ' + item.series.data[item.dataIndex][1] + ' Einträge');
        }
      } else {
        $("#tooltip1").remove();
        previousPoint = null;
      }
    });

    function showTooltip(x, y, contents) {
      $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: 100,
        left: x,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
      }).appendTo("#e1-container").fadeIn(0);
    }

  </script>
]]>
<div class="e1-container" id="e1-container">
  <div id="placeholder1" class="e1"></div>
</div>
 <![CDATA[ <script type="text/javascript"> 

This seems to be your problem, or at least the reason why FireBug does show html entities in your code. 这似乎是您的问题,或者至少是FireBug确实在您的代码中显示html实体的原因。 If you want to use cdata at all , you should place it inside of the <script> tags. 如果要使用cdata ,则应将其放在<script>标记内。

On why the tooltip is not shown at all, I can only guess, but for text content I'd recommend to use 关于为什么根本不显示工具提示的问题,我只能猜测,但是对于文本内容,建议使用

$('<div id="tooltip"></div>').text(contents)

instead of using it as a html string. 而不是将其用作html字符串。

You use appendTo() , which is fine. 您可以使用appendTo() ,这很好。 You append the node only when the plothover flot event is fired. 仅在触发plothover flot事件时才追加节点。 This is correct, too. 这也是正确的。 So your code looks fine, you should probably look into this: 因此,您的代码看起来不错,您可能应该考虑以下内容:

Jquery Flot "plothover" event not working jQuery Flot“ plothover”事件不起作用

EDIT: You also can put the JS <script> after the HTML. 编辑:您还可以将JS <script>放在HTML之后。

Do not directly add the contents inside the selector. 不要将内容直接添加到选择器中。

1) Create your DOM : var k = $('<div id="tooltip"></div>'); 1)创建您的DOM: var k = $('<div id="tooltip"></div>');

2) Fill your DOM : 2)填写您的DOM:

// Add after
k.append(contents);
// Replace 
k.html(contents);
// Replace and the content is just some text
k.text(contents);

3) Set the CSS : k.css({ ... }) 3)设置CSS: k.css({ ... })

4) Add the DOM to your page k.appendTo('#container'); 4)将DOM添加到您的页面中k.appendTo('#container'); . You can also use $('#container').html(k); 您也可以使用$('#container').html(k); to replace the container contents and avoid to have a duplicate 更换容器中的物品并避免重复

In short : 简而言之 :

var k = $('<div id="tooltip"></div>')
        .append(contents)
        .css({})
        .appendTo('#container');

NOTE: The best way is to already create your tooltip div and just fill the elements to avoid to create two div with same ID, ... If you are afraid it perturbs the page, add display : none; 注意:最好的方法是已经创建了您的工具提示div,并仅填充元素以避免创建具有相同ID的两个div,...如果您担心它会干扰页面,请添加display : none; to the CSS before to edit it, then change the classes when you edit it. 编辑CSS之前,先更改CSS,然后在编辑时更改类。

You will need to create div on 2 conditions : 您将需要在2个条件下创建div:

  • The pages is created on load with variable number of components 页面是在加载时创建的,具有可变数量的组件
  • You want to dynamically load CSS or JS. 您要动态加载CSS或JS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM