繁体   English   中英

如何使用那里的className而不是ID来判断单击了哪个按钮

[英]how to judge which button has been clicked using there className instead of ID

我在一个表中有100个按钮,这些表具有相同的类名,但ID为c-1,c-2,.... cn,不同<input type="button" class="btn-c" id="c-1" value="ADD">我将如何使用其className知道单击了哪个按钮,而在每个按钮<input type="button" ... onclick="call_function(this);"上却没有使用onclick事件<input type="button" ... onclick="call_function(this);" 为了简单起见,假设我要alert(button.id); 单击100个按钮中的任何一个

使用jQuery -附加一个单击处理程序的通用类和使用的情况下this获得点击的按钮ID

$(".btn-c").click(function() {
    alert(this.id); //id of the clicked button
});

如果您有太多按钮,则使用事件委托是有意义的:

$('table').on('click', '.btn-c', function() {
    alert(this.id); // will get you clicked button id
});

这是从性能角度出发的最佳方法,因为您仅将一个事件处理程序绑定到父元素并从子元素事件冒泡中受益。

UPD。 这是相同代码的纯JavaScript版本:

document.getElementById('table').addEventListener('click', function(e) {
    if (/\bbtn-c\b/.test(e.target.className)) {
        alert(e.target.id);
    }
}, false);

演示: http//jsfiddle.net/zn0os4n8/

您需要将事件附加到父元素并监听点击。 然后,您可以使用事件对象来确定要单击的内容。 您可以检查它是否是您想要的元素,然后做您想做的任何事情。

 document.body.addEventListener("click", function (e) { //attach to element that is a parent of the buttons var clickedElem = e.target; //find the element that is clicked on var isC = (clickedElem.classList.contains("c")); //see if it has the class you are looking for var outStr = isC ? "Yes" : "No"; //just outputting something to the screen document.getElementById("out").textContent = outStr + " : " + clickedElem.id; }); 
 <button class="d" id="b0">x</button> <button class="c" id="b1">y</button> <button class="c" id="b2">y</button> <button class="c" id="b3">y</button> <button class="d" id="b4">x</button> <div id="out"></div> 

注意:这在没有Polyfill的旧版IE中将无法使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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