javascript 给所有相同属性元素添加同一事件(javascript add the same event to all the same properties)

 

经常遇到要给 html 中所有相同属性的元素添加同一个点击事件, 这里, 我需要给所有 type 属性为 "radio" 的 input 元素添加上相同的点击事件, 具体实现的 javascript 代码如下:

 

// document.querySelectorAll("input[type='radio']")是获取网页上所有type属性为radio的input元素
document.querySelectorAll('.some-class').forEach(item => {
  item.addEventListener('click', event => {
    //handle click
  })
})

 

参考资料: https://flaviocopes.com/how-to-add-event-listener-multiple-elements-javascript/#:~:text=In%20JavaScript%20you%20add%20an%20event%20listener%20to,%28%29%20on%20multiple%20elements%20at%20the%20same%20time%3F

      https://stackoverflow.com/questions/40956717/how-to-addeventlistener-to-multiple-elements-in-a-single-line

      https://www.cnblogs.com/iyitong/p/4229355.html

 

具体例子如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" 
 6             integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 7     <title>Document</title>
 8 </head>
 9 <body>
10 
11     <div class="form_group">
12         <div class="form_group_radio" id="radio_div1">
13                 <input type = "radio" name = "optionRadio" id = "optionsRadios1" value = "option1" checked> 题目
14                 <input type = "radio" name = "optionRadio" id = "optionsRadios2" value = "option2"> 答案
15         </div>
16         <div class="form_group_input">
17             <input type="text" name="input_box1" id="input_row1" class="form-control" maxlength="10" style="width: 200px;">
18         </div>
19     </div>
20     
21     <div class="form_group">
22         <div class="form_group_radio">
23                 <input type = "radio" name = "optionRadio1" id = "optionsRadios3" value = "option1" checked> 题目
24                 <input type = "radio" name = "optionRadio1" id = "optionsRadios4" value = "option2"> 答案
25         </div>
26         <div class="form_group_input">
27             <input type="text" name="input_box2" id="input_row2" class="form-control" maxlength="10" style="width: 200px;">
28         </div>
29     </div>
30 <script>
31 
32     // document.querySelectorAll("input[type='radio']")是获取网页上所有type属性为radio的input元素
33     document.querySelectorAll("input[type='radio']").forEach(item=>{
34         item.addEventListener('click', event=>{
35             console.log(event.target.value);
36             if (event.target.value == "option1") {
37                 alert("option1");
38             } else {
39                 alert("option2");
40             }
41         })
42     })
43 </script>
44 </body>
45 </html>

结果如下图所示:

posted @ 2020-12-05 19:28  ttweixiao9999  阅读(1114)  评论(0编辑  收藏  举报