简体   繁体   中英

Avoid jquery append closing tag

How can I ensure that this:

$('.graph svg').append('<polyline points="' + '3,' +point+ ' 97,' +point+ '"style="fill:none;stroke:#FFFFFF;stroke-width:0.5"/>');

Actually results in a self closing tag ..../>

Rather than closing with </polyline>

For some reason only the former renders on iOS.

It doesn't result in any tags at all; it results in elements in the DOM. Tags are textual means of describing elements. When you give that string to jQuery, it asks the browser to parse that string and create elements (objects) in memory. The only tags involved are the ones you give to jQuery.


From your update (comment):

...is there another way of doing this that avoids the append method? Here's a fiddle that refuses to work on iOS http://jsfiddle.net/rCfrF/23

That doesn't work for me on Chrome, Firefox, or IE either. I don't think you can add to SVG elements like that, I think jQuery tries to create an HTML element polyline rather than the SVG polyline (which is namespaced).

This works on Chrome, Firefox, IE, and my iPhone 5: Updated version of your fiddle on JSBin (jsFiddle doesn't work properly on my iPhone 5)

function clickappend() {
    var svg = $("#graph svg")[0];
    var polyline = svg.ownerDocument.createElementNS('http://www.w3.org/2000/svg', 'polyline');
    polyline.setAttribute("points", "20,0 20,100");
    polyline.style.fill = "none";
    polyline.style.stroke = "#232323";
    polyline.style.strokeWidth = "0.5";
    svg.appendChild(polyline);
    alert('ran');
}

您可以使用:

$('.graph svg').html($('.graph svg').html() + '<polyline points="' + '3,' +point+ ' 97,' +point+ '"style="fill:none;stroke:#FFFFFF;stroke-width:0.5"/>');

This is the inspector's problem. There is a substantial difference between void elements (aka self-closing elements) and others, in that they cannot accept descendant nodes. polyline is such a void element. The inspector may show it as having a closing tag, but it shouldn't be able to accept methods such as – if you tried to insert content between its opening and closing tags that content would likely be inserted after it in the DOM.

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