jquery append() not writing closing tag

此生再无相见时 提交于 2019-12-24 03:55:36

问题


I'm having an odd issue with jquery append method in Google Chrome where it is not writing a closing tag when the element is empty but will if the element contains a character.

If I use this code:

$('#workZone .canvas').each(function(i) {
        $(this).append('<canvas id="test"></canvas>');
    });
}

I get this in the markup:

<canvas id="test">

If I use this code:

$('#workZone .canvas').each(function(i) {
        $(this).append('<canvas id="test">i</canvas>');
    });
}

the I get what I'd expect to get in the markup:

<canvas id="test">i</canvas>

I'd like the closing tag, obviously, but without having to include the throwaway character. What is going on?

Here is a test case on jsfiddle: http://jsfiddle.net/YSDnk/

Thanks!

Tim


回答1:


Try this:

$(this).append('<canvas id="test"><!-- //comment --> </canvas>');

You should put a html comment in empty spaces. This way the closing tag will show.




回答2:


Not sure how you are verifying this, but you are getting a full tag with your initial code. When I look at the Inspector I see what you see, but if run this in the console:

console.log($("#workZone .canvas").html())

In the print out you will see the full HTML as valid and properly closed.




回答3:


This is the same solution posted earlier, but with a blank space between the tags, in case the comment doesn't solve it.

$(this).append('<canvas id="test">&nbsp</canvas>');



回答4:


what if you use:

$(this).append('<canvas id="test"/>');

This is supposed to be equivalent to what you have, so I don't know why it would work, I've just learned to test all the quircks.



来源:https://stackoverflow.com/questions/12309372/jquery-append-not-writing-closing-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!