使用jQuery动态更改div的HTML会导致HTML编码丢失 [英] Dynamically changing the HTML of a div with jQuery is causing HTML encoding to be lost

查看:95
本文介绍了使用jQuery动态更改div的HTML会导致HTML编码丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,可以动态地改变名为'accordion'的div的HTML,如下所示:

  // htmlstring包含一些HTML,其中包含一些HTML编码
// eg < span class ='clickableComponent component'onclick =ComponentClicked('4612','Don&#39; t know','44761');>不知道< / span>
$('#accordion')。html(htmlstring);

但是,在设置元素'accordion'的HTML后,检查div的HTML通过FireBug(或其他开发人员工具),编码的撇号会丢失,取而代之的是未编码的撇号。编码似乎迷失在.html方法中。



我尝试了使用.innerHtml方法分配HTML,但同样的事情发生。 p>

有没有人有任何想法,为什么会发生这种情况?

解决方案

当HTML代码合并到DOM中时,所有内容都被规范化为内部DOM表示,原始的HTML代码无关紧要。撇号和&#39; 在HTML代码中是等价的,因此它们在DOM中变成了同样的东西。



你需要做的是逃避内撇号。 htmlstring 应该包含:

 < span class ='clickableComponent component' onclick =ComponentClicked('4612','Don''t know','44761');>不知道< / span> 

像这样的问题是为什么不推荐在HTML元素中内联Javascript的原因之一。它会更干净,如果你做了这样的事情:

  $(。clickableComponent)。click(function(){
ComponentClicked('4612',不知道,'44761');
});


I have a piece of code which dynamically alters the HTML of a div called 'accordion' on the fly like so:

// htmlstring contains some HTML containing some HTML encoding
// e.g. <span class='clickableComponent component' onclick="ComponentClicked('4612', 'Don&#39;t know', '44761');">Don't know</span>
$('#accordion').html(htmlstring);

However, after the HTML for the element 'accordion' is set, upon inspecting the HTML of the div via FireBug (or other developer tool) the encoded apostrophe is lost and is instead replaced by an apostrophe which is un-encoded. The encoding seems to get lost in the .html method.

I've tried using assigning the HTML using the .innerHtml method instead, but the same thing happens.

Does anybody have any ideas as to why this is happening?

解决方案

When the HTML code is merged into the DOM, everything is canonicalized into the internal DOM representation, the original HTML coding is irrelevant. Apostrophe and &#39; are equivalent in HTML code, so they turn into the same thing in the DOM.

What you need to do is escape the inner apostrophe. htmlstring should contain:

<span class='clickableComponent component' onclick="ComponentClicked('4612', 'Don\'t know', '44761');">Don't know</span>

Issues like this are one of the reasons why inline Javascript in HTML elements is not recommended. It would be cleaner if you did something like:

$(".clickableComponent").click(function() {
    ComponentClicked('4612', "Don't know", '44761');
});

这篇关于使用jQuery动态更改div的HTML会导致HTML编码丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆