简体   繁体   中英

How to use an option in a selection element to run a function depending on the selected option

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>

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 the select , not the click on the option elements. The latter is not very reliable across all browsers.

 $('#selector').on('change', e => { $('.item').removeClass('mySpecialClass'); $('.' + e.target.value).addClass('mySpecialClass'); });
 .mySpecialClass { background-color: #C00; color: #FFF; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select id="selector" class="selector"> <option selected>Preset</option> <option value="item1">item1</option> <option value="item2">item2</option> <option value="item3">item3</option> </select> <div class="item item1">item1</div> <div class="item item2">item2</div> <div class="item item3">item3</div> <div class="item item1 item2">item1 item2</div> <div class="item item3 item2">item3 item2</div> <div class="item item1 item3">item1 item3</div> <div class="item item2 item3">item2 item3</div> <div class="item item1 item2 item3">item1 item2 item3</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM