jQuery 如何在特定位置添加列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2932179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a list-item at specific position
提问by Germanico Brismal
I'd like to add a <li>
at a specific position, for example:
我想<li>
在特定位置添加一个,例如:
<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?
假设我想添加一个新的<li>
below/after <li>Position 2</li>
,我该如何使用 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>
.
但是,它没有工作,因为它附加的<li>
内部<li>Position 2</li>
,而不是添加<li>
以下/后<li>Position 2</li>
。
Can someone give me some help?
有人可以给我一些帮助吗?
Thank you.
谢谢你。
回答by Felix Kling
You have to use after()
instead of append()
:
你必须使用after()
而不是append()
:
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:
的文档append()
清楚地说:
Insert content (...) to the endof each element.
将内容 (...) 插入到每个元素的末尾。
For completeness:
为了完整性:
Note that :eq(n)
matches the n
th element of the matching element set, whereas :nth-child(n)
matches the n
th child of the parent.
请注意,:eq(n)
匹配n
匹配元素集的第 th 个元素,而:nth-child(n)
匹配n
父元素的第 th 个子元素。
回答by emmanuel
You should use after()
or insertAfter()
http://api.jquery.com/category/manipulation/dom-insertion-outside/
您应该使用after()
或insertAfter()
http://api.jquery.com/category/manipulation/dom-insertion-outside/
回答by jay
$('<option val="position3">Position3</option>').insertAfter('#list :nth-child(<give childnumber here>)')
index start with 1
索引从 1 开始