簡體   English   中英

具有相同類的多個按鈕的單擊事件上的Javascript

[英]Javascript on click event for multiple buttons with same class

我在我正在構建的網站上有幾個按鈕,某些按鈕有一個類,而其他按鈕有另一個。 我想要做的是找到找到點擊按鈕的最佳方法,而無需為每個單獨的按鈕設置事件偵聽器。 我想出了以下 2 個 for 循環來查找所有具有 button-1 類和 button-2 類的按鈕。 作為 javascript 的新手,我只是不想養成壞習慣,因此將不勝感激有關實現這一目標的最佳方法的任何建議。

<section>
  <div class="button--1"></div>
  <div class="button--1"></div>
  <div class="button--2"></div>
</section>

<section>
  <div class="button--2"></div>
  <div class="button--1"></div>
  <div class="button--2"></div>
</section>

 var button1 = document.querySelectorAll('.button--1');
    var button2 = document.querySelectorAll('.button--2');

    for (var a = 0; a < button1.length; a++) {    
        button1[a].addEventListener('click',function(){
            //do something
        });
    }

    for (var b = 0; b < button2.length; b++) {
        button1[b].addEventListener('click',function(){
            //do something
        });
    }

如果您計划擁有多個其他類,例如button--3 , …4…15
您必須希望以“button”為目標,以類開頭( ^= )的所有div元素為目標:

(請注意,您也可以在 CSS 中執行此操作!)

 var allButtons = document.querySelectorAll('div[class^=button]'); console.log("Found", allButtons.length, "div which class starts with “button”."); for (var i = 0; i < allButtons.length; i++) { allButtons[i].addEventListener('click', function() { console.clear(); console.log("You clicked:", this.innerHTML); }); }
 /* Some styling */ section { margin: 8px 0; border: 1px solid gray; } section div { border: 1px solid lightgray; display: inline-block; margin-left: 8px; padding: 4px 8px; width: 30px; } section div[class^=button] { background: lightgray; cursor: pointer; }
 <span>You can click on the buttons:</span> <section> <div class="button--1">s1-1</div> <div class="button--2">s1-2</div> <div class="button--3">s1-3</div> <div class="button--4">s1-4</div> </section> <section> <div class="button--1">s2-1</div> <div class="button--2">s2-2</div> <div class="button--3">s2-3</div> <div class="button--4">s2-4</div> </section> <section> <div class="not-a-button">not1</div> <div class="not-a-button">not2</div> <div class="not-a-button">not3</div> <div class="not-a-button">not4</div> </section>

希望能幫助到你。

嘗試使用事件委托

 (function() { document.body.addEventListener("click", clickButtons); // ^ one handler for all clicks function clickButtons(evt) { const from = evt.target; console.clear(); if (!from.className || !/button--\\d/i.test(from.className)) { return; } // ^check if the element clicked is one of the elements you want to handle // if it's not one of the 'buttons', do nothing console.log("you clicked " + from.classList); } }())
 .button--1:before, .button--2:before { content: 'BTTN['attr(class)']'; } .button--1, .button--2 { border: 1px solid #999; background: #eee; width: 220px; padding: 3px; text-align: center; }
 <section> <div class="b1 button--1 section1"></div> <div class="b2 button--1 section1"></div> <div class="b3 button--2 section1"></div> </section> <section> <div class="b4 button--2 section2"></div> <div class="b5 button--1 section2"></div> <div class="b6 button--2 section2"></div> </section>

您可以在querySelctorAll()的字符串中使用多個選擇器,方法是用,

 var button1 = document.querySelectorAll('.button--1'); var button2 = document.querySelectorAll('.button--2'); var allButtons = document.querySelectorAll('.button--1, .button--2'); console.log(button1.length); console.log(button2.length); console.log(allButtons.length);
 <section> <div class="button--1"></div> <div class="button--1"></div> <div class="button--2"></div> </section> <section> <div class="button--2"></div> <div class="button--1"></div> <div class="button--2"></div> </section>

當在單個元素上按下並釋放指針設備按鈕(通常是鼠標的主按鈕)時,將觸發click事件。

本文檔將幫助您了解它是如何工作的MDN - 單擊事件

我的建議是使用jQuery,以便您可以執行以下操作:

$(document).on('click', '.button--1', function() {
   // Do something
});

$(document).on('click', '.button--1', function() {
   // Do something
})

但是對於純 Javascript 來說,一個干凈的方法是創建一個綁定事件回調的函數。

function bindEvent(callback, eventType, targets) {
   targets.forEach(function(target) {
     target.addEventListener(eventType, callback);
   });
};


var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');

bindEvent(function() {
   // do something
}, 'click', button1);

bindEvent(function() {
   // do something
}, 'click', button2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM