如何在选择元素中使用选项根据选定选项运行功能
我的目的是在选择器元素上使用选定的选项(item01)来运行特定函数,然后使用与对应于对应的对象的IDS,将类应用于数组(array01)内部的每个对象(array01)网页的另一部分。
这就是我写的,但是我不知道该怎么做才能使它起作用。
let array01 = [{id:"07-01"}, {id:"05-01"}, {id:"05-03"}, {id:"05-05"}, {id:"05-07"}, {id:"05-09"}, {id:"05-11"}, {id:"05-13"}, {id:"05-05"}, {id:"06-05"}, {id:"07-08"}, {id:"07-11"}, {id:"06-13"}]
const test = array01.map(item => item.id);
$("#item1").on("click", function() {
test.forEach(element => (("#" + element).addClass("mySpecialClass")));
});
<select id="selector" class="selector">
<option selected>Preset</option>
<option value="item1" class="item1" id="item1">item1</option>
<option value="item2" class="item2" id="item2">item2</option>
<option value="item3" class="item3" id="item3">item3</option>
</select>
I aim to use a selected option (item01) on a selector element to run a specific function and this function should then apply a class to each of the objects inside of the array (array01) using the ids of the objects that correspond to elements on a different part of the web page.
This is what I have written, but I can not figure out what to do to make it work.
let array01 = [{id:"07-01"}, {id:"05-01"}, {id:"05-03"}, {id:"05-05"}, {id:"05-07"}, {id:"05-09"}, {id:"05-11"}, {id:"05-13"}, {id:"05-05"}, {id:"06-05"}, {id:"07-08"}, {id:"07-11"}, {id:"06-13"}]
const test = array01.map(item => item.id);
$("#item1").on("click", function() {
test.forEach(element => (("#" + element).addClass("mySpecialClass")));
});
<select id="selector" class="selector">
<option selected>Preset</option>
<option value="item1" class="item1" id="item1">item1</option>
<option value="item2" class="item2" id="item2">item2</option>
<option value="item3" class="item3" id="item3">item3</option>
</select>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
做您需要的最简单方法是匹配应该将类的元素与所选选项值的值匹配。在下面的示例中,我通过将类放置在HTML中的元素进行分组来完成此操作。
请注意,在下面的示例中,它使用
更改
选择
的事件,而不是
。后者在所有浏览器中都不是很可靠。在
option>选项
elements上单击The simplest way to do what you require would be to match the elements which should have the class to the selected option's value. In the example below I've done this by placing the classes to group the elements in the HTML.
Note in the example below that it's using the
change
event of theselect
, not theclick
on theoption
elements. The latter is not very reliable across all browsers.