jQuery - 检查单击了哪个按钮

时间:2015-02-22 23:10:02

标签: javascript jquery

我有两个按钮:

<input type="button" name="hideAll" value="Hide Descriptions"/>
<input type="button" name="showAll" value="Show Descriptions"/>

使用jQuery,如何判断单击了哪个按钮?

2 个答案:

答案 0 :(得分:0)

添加按钮共享的课程......

<input class="mybutton" type="button" name="hideAll" value="Hide Descriptions"/>
<input class="mybutton" type="button" name="showAll" value="Show Descriptions"/>

$(function() {
    $('.mybutton').on('click', function() {
        var isClicked = this.attr('name');

        if (isClicked === 'hideAll') {
           ...
        }
        if (isClicked === 'showAll') {
           ...
        }
    });
});

根据您的需求和范围,您还可以使isClicked成为一个全局变量,该变量将在点击事件之外提供。

isClicked = this.attr('name');

答案 1 :(得分:0)

$('input[type="button"]').on('click', function() {
    // which button was clicked?
    alert($(this).attr('name') + ' was clicked');
});