如何在特定位置添加列表项 [英] How to add a list-item at specific position
问题描述
我想添加一个<立GT;
在特定的位置,例如:
< UL ID =清单>
<立GT;职位1 LT; /李>
<立GT;位置2'; /李>
<立GT;位置4℃; /李>
< UL>
让我们说,我想添加一个新的<李>
低于/后<李>位置2'; /李>
,我怎么能使用jQuery吗?
我试着用下面的code做到这一点:
$('#名单里:EQ(1))追加('<立GT;位置3'; /李>');
但是,它没有工作,因为它追加<李>
的&LT内部;李>位置2'; /李>
,而不是添加<李>低于
/后的<李>位置2'; /李>
。
有人可以给我一些帮助?
感谢您。
您必须使用 ()后
而不是追加()
:
说明:插入内容,由参数指定,在匹配的元素集合中的每个元素之后,
块引用>$('#名单里:EQ(1))。之后('<立GT;位置3'; /李>');
)的文档附加(
清清楚楚地写着:
插入内容(...)以每个元素的结尾
块引用>有关完整性:
注意
:EQ(N)
匹配N
个匹配的元素集合的元素,而<一HREF =http://api.jquery.com/nth-child-selector/>:第n个孩子(N)
的<$ C匹配$ C> N 个母的孩子。I'd like to add a
<li>
at a specific position, for example:<ul id="list"> <li>Position 1</li> <li>Position 2</li> <li>Position 4</li> <ul>
Let's say that I want to add a new
<li>
below/after<li>Position 2</li>
, how can I do it using jQuery?I've tried to do it using the code below:
$('#list li:eq(1)').append('<li>Position 3</li>');
But, it didn't work, because it appends the
<li>
inside the<li>Position 2</li>
, instead add the<li>
below/after the<li>Position 2</li>
.Can someone give me some help?
Thank you.
解决方案You have to use
after()
instead ofappend()
:Description: Insert content, specified by the parameter, after each element in the set of matched elements.
$('#list li:eq(1)').after('<li>Position 3</li>');
The documentation of
append()
clearly says:Insert content (...) to the end of each element.
For completeness:
Note that
:eq(n)
matches then
th element of the matching element set, whereas:nth-child(n)
matches then
th child of the parent.这篇关于如何在特定位置添加列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!