gpt4 book ai didi

javascript - 使用 selects 和 javascript

转载 作者:搜寻专家 更新时间:2023-11-01 05:26:29 24 4
gpt4 key购买 nike

我的代码是:

<select name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>

<select name='other'>
<option>Rats</option>
<option>Cats</option>
<option>Oranges</option>
<option>Audi</option>
</select>

如何过滤我的第二个 <select> ,所以它只会显示我想要的项目,例如。如果我选择动物,我的选择将是:

<select name='other'>
<option>Rats</option>
<option>Cats</option>
</select>

如果我选择“食物”,我的 <select>看起来像:

<select name='other'>
<option>Oranges</option>
</select>

好吧,我希望你明白了。谢谢。

最佳答案

您需要在选择之间创建某种关联,我建议使用 data-*属性:

<select id="main_select" name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>

<select id="other_select" name='other'>
<option data-category="Animals">Rats</option>
<option data-category="Animals">Cats</option>
<option data-category="Food">Oranges</option>
<option data-category="Cars">Audi</option>
</select>

一旦所有 <option> 就绪元素,JavaScript 代码看起来像这样:

已编辑,这有效:

$(function() {
var cloned = $('#other_select option').clone();
$('#main_select').change(function() {
var selectedCategory = $(':selected', this).text();
var filtered = $(cloned).filter("[data-category='" + selectedCategory + "']");
$("#other_select option").replaceWith(filtered);
});
$('#main_select').change(); //fire the event initially.
});

jsFiddle example

关于javascript - 使用 selects 和 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4535636/

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