简体   繁体   中英

jQuery insertAfter: will insert <li> but not <a>?

With this code:

<ul data-role="listview" id="routelist" data-theme="g">
<li id="firstlistitem" style="display:none;">

$("<li><a href='http://www.google.co.uk'></a></li>").text('content').insertAfter($("#firstlistitem"));  

and see also this jsFiddle: http://jsfiddle.net/6MW2e/

How come I end up with an unlinked list item? How can I insert an element with a link?

thanks!

Because you're setting the text of the outer element (the <li> ) and not the inner element (the link).

If you're going to keep that syntax, you could try:

$('<li></li>')
    .append(
        $('<a href="www.google.co.uk"></a>').text('content'))
    .insertAfter($('#firstlistitem'));

It seems to me that it would be much cleaner if you simply did:

$('<li><a href="www.google.co.uk">' + content + '</a></li>')
    .insertAfter($('#firstlistitem'));

Your overwriting the text of the <li> when you call .text("content")

$("<li/>", {
    html: $("<a/>", { href: "http://www.google.co.uk", text: content })
}).appendTo("#routelist");

http://jsfiddle.net/hunter/6MW2e/5/

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