gpt4 book ai didi

javascript - jQuery 移动特定选项顶部选择的顶部(下拉)

转载 作者:搜寻专家 更新时间:2023-10-31 21:55:28 24 4
gpt4 key购买 nike

我主要是尝试从选择中选取一个特定选项并将其移至列表顶部。我现在要做的就是这个。

$("select[name=list]").find('option[value="car"]').insertBefore($("select[name=list]").find('option:eq(1)'));

出于某种原因,它执行了两次,在顶部留下了两个选项

<option value="car">Car</option>
<option value="car">Car</option>

不确定我做错了什么,也许有人知道?

谢谢。

最佳答案

来自 jQuery 文档:

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned) and a new set consisting of the inserted element is returned.

[..]

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

所以,有线索了!我的猜测是您的选择器包含太多元素,并且您选择了不止一个元素......甚至在文档的另一个选择列表中也是如此。

您可以为您的示例提供更多的 HTML 代码,但让我展示一下我将如何做...

HTML

<select id='MyNiceList'>
<option value='my_option_1'>First Option</option>
<option value='my_option_2'>Second Option</option>
<option value='my_option_3'>Third Option</option>
</select>

Js

$('#MyNiceList option[value="my_option_2"]').insertBefore('#MyNiceList option[value="my_option_1"]');

如果您注意我使用的选择器,我排除了选择多个元素的任何可能性,因此,遵守我引用的第二部分的规则。

示例:

http://jsfiddle.net/sASCg/1/

希望我的第一个回答对您有所帮助! :)

关于javascript - jQuery 移动特定选项顶部选择的顶部(下拉),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22330220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com