[英]Why am I losing my characters from my html string when trying to add html dynamically using javascript
I have a page that I am trying to dynamically add some links to. 我有一个页面,我试图动态添加一些链接。 The links are getting added to the page fine, but the '[' and ']' at either end of the line are getting dropped. 链接可以很好地添加到页面上,但是该行任一端的'['和']'都可以删除。 The code from my .js file is: 我的.js文件中的代码是:
var html = "[ <a href='#'>Change</a> | <a href='#'>Remove </a> ]";
$(html).appendTo("#id123");
The result I want is: 我想要的结果是:
[ <a href='#'>Change</a> | <a href='#'>Remove</a> ]
The result I'm getting is: 我得到的结果是:
<a href='#'>Change</a> | <a href='#'>Remove</a>
If I wrap the line in a <span>
tag like so: 如果我将行包装在<span>
标记中,如下所示:
var html = "<span>[ <a href='#'>Change</a> | <a href='#'>Remove </a> ]</span>";
$(html).appendTo("#id123");
it renders as expected. 它呈现预期的效果。 I set a breakpoint on the code and checked the html var right before the .appendTo and it contains the '[' and ']'. 我在代码上设置了一个断点,并在.appendTo之前检查了html var,它包含了[[和']'。
Anyone know why this is happening? 有人知道为什么会这样吗? Are '[' and ']' special character that need escaped and I'm just forgetting that fact? 是否需要转义'['和']'特殊字符,而我只是忘记了这一事实?
When you wrap your html variable inside of "$()", it creates a jQuery object out of it. 当将html变量包装在“ $()”内时,它会从中创建一个jQuery对象。 That object removes anything that's outside of a markup tag (like <a> or <span>). 该对象将删除标记标签之外的所有内容(例如<a>或<span>)。 You can take out the"[" and put "TESTING THIS" in it's place and you'll see it still won't show up. 您可以取出“ [”并在其中放置“ TESTING THIS”,然后您仍然会看到它不显示。
So that's why you're losing it in your output. 这就是为什么您在输出中丢失它的原因。
No, those are just not valid XHTML. 不,那些只是无效的XHTML。 If you put the '[' and ']' in their own spans, like so: 如果将'['和']'放在自己的跨度中,如下所示:
"<span>[ </span><a href='#'>Change</a> | <a href='#'>Remove </a></span> ]</span>"
You would also get your expected text. 您还将获得您期望的文本。 jQuery will parse and create valid HTML, and the brackets aren't contained in an element. jQuery将解析并创建有效的HTML,并且括号不会包含在元素中。
I'm not sure why this happens. 我不确定为什么会这样。 It seems like something internal to the appendTo()
I tried it with append()
and it worked out fine. 看起来好像是appendTo()
内部的东西,我使用append()
尝试了一下,效果很好。 So you could write $("#id123").append(html)
因此,您可以编写$("#id123").append(html)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.