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:
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:
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 bef开发者_StackOverflow社区ore the .appendTo and it contains the '[' and ']'.
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. That object removes anything that's outside of a markup tag (like <a> or <span>). You can take out the"[" and put "TESTING THIS" in it's place and you'll see it still won't show up.
So that's why you're losing it in your output.
No, those are just not valid 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.
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. So you could write $("#id123").append(html)
精彩评论