【问题标题】:how to judge which button has been clicked using there className instead of ID如何使用那里的className而不是ID来判断单击了哪个按钮
【发布时间】:2014-10-17 18:04:14
【问题描述】:

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

【问题讨论】:

标签: javascript


【解决方案1】:

如果你有这么多按钮,使用事件委托是有意义的:

$('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/

【讨论】:

  • 我可以使用 jquery,但我只能使用 javascript 而不是 jquery 之类的任何库
【解决方案2】:

使用 jQuery - 将单击处理程序附加到公共类并使用 this 的实例来获取单击按钮的 id

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

【讨论】:

  • 我想用 java-script 代替 Jquery
【解决方案3】:

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

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。

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2011-02-10
    • 2011-04-04
    • 2016-06-03
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多