确定使用jQuery按下了哪个按钮

时间:2012-01-06 18:48:45

标签: jquery

假设我在一个父“div”中有三个“按钮”元素。假设这些按钮可以使用jQuery标记为1,2,3或0,1,2,是否有一种简单的方法来确定单击哪个按钮的数量?

这是HTML:

<div class="table-tabs">
    <button class="tab1 selected">Description</button>
    <button class="tab2">Monitoring</button>
    <button class="tab3">Change Logs</button>
</div>

我想知道这个号码,以便在按下按钮时激活相应的表格。

4 个答案:

答案 0 :(得分:3)

您可以使用.index()获取按钮的编号(盯着0)。

$('.table-tabs button').click(function(){
    console.log($(this).index('.table-tabs button'));
});

DEMO:http://jsfiddle.net/UPKgm/

或者,您可以解析class并获取标签号,但这需要更多工作。

$('.table-tabs button').click(function() {
    var classes = $(this).attr('class').split(' '),
        tabID;
    $.each(classes, function() {
        if (this.indexOf('tab') === 0) {
            tabID = this.replace('tab', '');
            return false;
        }
    });
    console.log(tabID);
});

DEMO:http://jsfiddle.net/UPKgm/1/

答案 1 :(得分:0)

试试这个:

$('.table-tabs button').click(function(){

var btn = $(this).html();

alert(btn);

});

答案 2 :(得分:0)

只需捕获单击的按钮。 :)

http://jsfiddle.net/MetalFrog/9dDy9/5/

修改:已更新以匹配您的示例HTML。

$(function(){
    $('.table-tabs button').click( function(){
       console.log( $(this).text() );
    }); 
});

答案 3 :(得分:0)

假设您输入了type按钮,其中数字设置为输入值, 你可以使用jQuery选择器来选择类型按钮的所有输入,然后为将读取值的click事件添加一个函数:

HTML:

<div>
    <input type="button" value="1" />
    <input type="button" value="2" />
    <input type="button" value="3" />
</div>

JavaScript的:

$(":input[type='button']").click(function() {
        alert($(this).val());
    }
)

示例:http://jsfiddle.net/M6v5b/

相关问题