将唯一点击事件分配给数组JS的每个重复实例

问题描述 投票:0回答:3

这里是具有相同重复实例且没有唯一标识符的三种形式的示例:

<form action="/haters"><input type="submit" value="stop hatin"></form>
<form action="/haters"><input type="submit" value="stop hatin"></form>
<form action="/haters"><input type="submit" value="stop hatin"></form>

如何将不同的console.log或通过单击触发的任何消息附加到每个按钮?

到目前为止,我已经使用jQuery Dom选择器$("form[action='/haters']")定位了这些按钮>

我也在Codepen上发布了:http://codepen.io/marc313/pen/uphiv

这里是具有相同重复实例且没有唯一标识符的三种形式的示例:

] >

尽管您可以分别绑定到每个按钮,如@Deryck的回答,但通常这种做法会导致代码重复。单击3个按钮,您的实际用例可能不是将3种不同的东西记录到控制台。

特别是如果这三个按钮执行相似的操作,或者它们作用于同一组数据,则通常更干净地执行以下操作:

jQuery
$('document').on('click', 'form[action=haters]', function() {
    /* This event will fire for any form with action="haters"
     * that is on your page. */

    var $clickedElement = $(this); // jQuery collection of the clicked element

   /* If you slightly modify your markup, as in the example below, you can
    * quickly uniquely identify each button, and act accordingly, like so: */

    var id = $clickedElement.attr('data-id');

    if(id === 1) {
        stuffForFirstButton();
    } else if(id === 2) {
        stuffForSecondButton();
    } else if(id === 3) {
        stuffForThirdButton();
    }
});

标记

<form action="/haters"><input type="submit" value="stop hatin" data-id="1"></form>
<form action="/haters"><input type="submit" value="stop hatin" data-id="2"></form>
<form action="/haters"><input type="submit" value="stop hatin" data-id="3"></form>

参考

集合中的每个项目都有一个index号,您可以用它来识别它们。

jQuery:
$('input[type=submit]').eq(0).on('click', function() {
    console.log('This is unique to the FIRST submit button');
});
$('input[type=submit]').eq(1).on('click', function() {
    console.log('This is unique to the SECOND submit button');
});    
$('input[type=submit]').eq(2).on('click', function() {
    console.log('This is unique to the THIRD submit button');
});

[The .eq() method表示“等于”,指的是您在.eq()中选择的选择器的索引号。

如果要系统地]执行此操作,则可以将其放入$('input[type=submit'])for()循环中。当然,您可以将while()替换为要用来标识按钮的任何数字(从0开始是集合中的第一个元素,但不大于eq(0))。

这是您的$('input[type=submit]').length的叉子,可以在CodePen上查看它的运行情况>

我认为最好的方法是在此输入中添加名称,以后您可以按名称获取每个输入并为每个输入使用单击功能。

alert()
javascript jquery arrays jquery-events
3个回答
1
投票

尽管您可以分别绑定到每个按钮,如@Deryck的回答,但通常这种做法会导致代码重复。单击3个按钮,您的实际用例可能不是将3种不同的东西记录到控制台。


1
投票

集合中的每个项目都有一个index号,您可以用它来识别它们。


0
投票

我认为最好的方法是在此输入中添加名称,以后您可以按名称获取每个输入并为每个输入使用单击功能。

alert()
© www.soinside.com 2019 - 2024. All rights reserved.