如何使按钮列表从不同的元素中侦听事件

时间:2017-01-18 21:22:08

标签: javascript jquery html5

我有一个网页,其中包含可变数量的" slave"应该听"主人"单击按钮。见下图:

Buttons on webpage

我想使用jQuery连接事件,以便当" master"单击按钮,为我的每个" slave"调用一个JavaScript函数。纽扣。我想要每个人"奴隶"按钮,用于收听" master"按钮。每个"奴隶" button的class属性设置为class="btn btn-default slaveButton",我可以使用class" slaveButton"得到所有"奴隶"按钮使用jQuery的类选择器。由于"奴隶"按钮是可变的,我不知道如何在JavaScript中设置它,一个例子会很好。

每个"奴隶" button上有一个HTML5数据属性,其列表中的索引(即1,2,3,4)将传递给ajax请求。

1 个答案:

答案 0 :(得分:1)

在我看来,你已经知道该怎么做了。

//wire up event listener for master button
$("#master-button").click(function() {
    //your master button was clicked.
    //loop over all the slave buttons
    $(".slaveButton").each(function( index, btnElement) {
        //index shows the place of the slaveButton in the list/dom
        console.log("your button element is", this, "and was triggered when" , $("#master-button").get(0) , "was clicked);
    });
});