开发者

Why I can not use a variable for the :eq filter to append data to an unordered list?

Why I can not use a variable counter for the :eq filter to append data to an unordered list?

For example, the code is not working. It not being updated into the div of un开发者_开发问答ordered list.

 $('#list li:eq("+ counter +")').append('<li>' + variable + '<li>');


Correct syntax:

$('#list li:eq(' + counter +')')

You must use the same string delimeters, can't mix them in same string.

More elegant syntax would be:

$('#list li').eq(counter)

This way no need to mess with string delimeters at all.


In addition to the string issue that Shadow Wizard mentions, if you're trying to add another li tag on the same level as #list li, then you're code isn't right. Append, will add a child so:

$('#list li').eq(n).append('<li>' + variable + '</li>')

adds an LI tag inside the nth LI tag, not after the nth LI tag. From the jQuery doc:

The .append() method inserts the specified content as the last child of each element in the jQuery collection

You may be interested in the .after() method if what you're trying to do is to insert a new LI tag after an existing LI tag, but at the same level:

$('#list li').eq(n).after('<li>' + variable + '</li>')

See here http://jsfiddle.net/jfriend00/PHkm4/ for a working example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜