jquery append() not writing closing tag

2019-07-09 04:03发布

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

标签: jquery append
4条回答
Anthone
2楼-- · 2019-07-09 04:14

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-07-09 04:17

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.

查看更多
别忘想泡老子
4楼-- · 2019-07-09 04:17

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>');
查看更多
在下西门庆
5楼-- · 2019-07-09 04:28

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.

查看更多
登录 后发表回答