简体   繁体   中英

jQuery appendTo - prevent adding of closing tag

I am building an anchor tag as follows:

$('<a href="javascript: void(0)" xml = "' + MapLayerSourceInfo + '"onclick=" EditXmlDataEditor(this)">Edit</a>').appendTo(container);

If MapLayerSourceInfo has the value <source_info></source_info> I get the following, which is what I want.

<a href="javascript: void(0)" xml="<source_info></source_info>" onclick=" EditXmlDataEditor(this)">&lt;......&gt;</a>

If however MapLayerSourceInfo has the value <source_info />, jQuery appendTo gives me this:

<a href="javascript: void(0)" xml="<source_info></a>" onclick=" EditXmlDataEditor(this)">&lt;......&gt;</a>

It adds the closing tag for the anchor. How do I prevent this?

You should either escape the string or use a different syntax for creating the element:

$('<a>', {
    xml: MapLayerSourceInfo,
    text: 'Edit',
    href: '#',
}).appendTo(container);

http://jsfiddle.net/mgm7egcq/

Using above syntax you force the jQuery to use the attr method behind the scene. As a suggestion, avoid using onclick attribute, it makes your code unmaintainable and generally is a bad practice. For dynamically generated elements you can delegate the events.

You have toe escape your characters within the html attributes, you can use somthing like underscores escape or write your own

http://underscorejs.org/#escape

So what you'll need to do is

$('<a href="javascript: void(0)" xml = "' + escape(MapLayerSourceInfo) + '"onclick=" EditXmlDataEditor(this)">Edit</a>').appendTo(container);

Where escape is something like:

function escapeHTML(s) { 
    return s.replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

Basically any xml characters in the dom will be interpreted as such and the browser will try fix the dom because they are part of it so if you escape them you should be fine. Don't worry any js like $("selector for your link").attr("xml") will return the orginal xml.

You could transform <source_info/> into <source_info></source_info>

    if (MapLayerSourceInfo == "<source_info/>"){
 MapLayerSourceInfo = "<source_info></source_info>"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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