[英]Append option at random position in select element?
<select>
<option>One</option>
<option>Two</option>
</select>
I would like to append a new option
between first and second option
using javascript.我想使用 javascript 在第一个和第二个
option
之间附加一个新option
。
Required result :要求的结果:
<select>
<option> One </option>
<option> New </option>
<option> Two </option>
</select>
Try this:尝试这个:
$('<option> New </option>').insertBefore('select option:nth-child(2)');
insertBefore
will append the element before the selector indicated. insertBefore
将在指定的选择器之前附加元素。 In this case we choose the 2nd child option
of our select.在这种情况下,我们选择我们选择的第二个子
option
。 Remember that nth-child
is not zero-based index.请记住,
nth-child
不是从零开始的索引。
JSFiddle : https://jsfiddle.net/58209tgu/ JSFiddle : https : //jsfiddle.net/58209tgu/
使用eq(index)
$('<option />').text('New').insertAfter('select option:eq(0)');
In jQuery, you can use insertAfter function.在 jQuery 中,您可以使用 insertAfter 函数。
Documentation:文档:
http://api.jquery.com/insertafter/ http://api.jquery.com/insertafter/
Example HTML:示例 HTML:
<select>
<option id='insertAfterMe'>One</option>
<option>Two</option>
</select>
Example jQuery:示例jQuery:
$(function(){
$('<option>new option</option>').insertAfter('#insertAfterMe');
});
jsFiddle: js小提琴:
https://jsfiddle.net/fx7xxhvq/ https://jsfiddle.net/fx7xxhvq/
If you don't want to put an id on the element you want to insert after, any valid selector will work, such as the nth-child selector mentioned in the other answer.如果您不想在要插入的元素上放置 id,则任何有效的选择器都可以使用,例如另一个答案中提到的第 n 个子选择器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.