简体   繁体   English

使用for循环将事件与jQuery绑定到多个元素

[英]Binding events with jQuery to multiple elements with a for loop

So I'm working on this think where I need to generate elements and then bind events to them. 所以我正在研究这个问题,我需要生成元素,然后将事件绑定到它们。 Every time I generate an element I unbind and rebind the events to the generated elements with a for loop. 每次我生成一个元素时,我解除绑定并用for循环将事件重新绑定到生成的元素。 These functions seem to trigger, but they get the wrong index (which tells the code which element to work with). 这些函数似乎触发了,但它们得到了错误的索引(它告诉代码使用哪个元素)。

Check out the code at jsFiddle http://jsfiddle.net/6UgYe/4/ 查看jsFiddle http://jsfiddle.net/6UgYe/4/上的代码

Anything modular that solves this will do. 解决这个问题的任何模块化都可以。 Also feel free to comment on my code. 也可以随意评论我的代码。 I wrote most of this last year when I had just begun with javascript. 我刚刚开始使用javascript时写了大部分内容。

Regards, 问候,

Akke Akke

EDIT: Here is the solution in action: http://jsfiddle.net/nwH8Z/3/ it calculates VAT-Free prices on blur. 编辑:这是行动的解决方案: http//jsfiddle.net/nwH8Z/3/它计算模糊的增值税免费价格。

Change your bindEmAll function to look like this - bindEmAll函数更改为如下所示 -

function bindEmAll()
{
    $('#container').on('blur', 'input[id$=".5"]', function(){

     $('#Errorfield').append('Current box is ' + this.id + '<br/>').append(num_format(this.value) + '<br />')  

})
}

It makes all input boxes with IDs that end in '.5' append their ids and values, handled by your num_format() function, to #Errorfield . 它使所有带有以“.5”结尾的ID的输入框将其由num_format()函数处理的id和值附加到#Errorfield The event handler is attached to all input boxes inside #container , even if they are added dynamically. 事件处理程序附加到#container 所有输入框,即使它们是动态添加的。

And remove bindEmAll() from your click handler for #addTT ; 并删除bindEmAll()从你的点击处理程序#addTT ; otherwise the event handlers will be bound as many times as you've clicked addTT, which makes things quite messy ;-) 否则事件处理程序将被绑定多次,因为你点击addTT,这使得事情相当混乱;-)

$('#addTT').click(function() {
    addTT('#container');
});

Updated fiddle here . 这里更新了小提琴。

The problem is happening because the blur event handler is not being run until well after the loop finished. 问题正在发生,因为blur事件处理程序直到循环结束后才运行。 The order of execution is: 执行顺序是:

  • Attach event handler to blur event on item 1 将事件处理程序附加到项目1上的模糊事件
  • Attach event handler to blur event on item 2 附加事件处理程序以模糊第2项上的事件

...some time later... ...一段时间之后...

  • Actually invoke the blur event 实际上调用模糊事件

By the time your event handler is invoked the value of the variable i from the loop has changed to the index of the last value, so that is what is being used in the event handler. 在调用事件处理程序时,循环中变量i的值已更改为最后一个值的索引,因此这是事件处理程序中使用的值。

To get around this you can just put your code inside a closure: 要解决这个问题,您可以将代码置于闭包中:

 (function(i) {
        $('#container input#box' + i + '\\.5').unbind();
        $('#container input#box' + i + '\\.5').blur(function() {
            //error processing function;
            $('#Errorfield').append('Current box is $(\'#container input#box' + i + '\\.5\')<br />');

        });
        $('#container input#box' + i + '\\.5').blur(function() {
            $('#container input#box' + i + '\\.5').val(num_format($('#container input#box' + i + '\\.5').val()));
            $('#Errorfield').append('Current box is $(\'#container input#box' + i + '\\.5\')<br />');
        });
    })(i);

I've updated your fiddle here 我在这里更新了你的小提琴

  boxes = 1;

        function num_format(input) {
            //For demo purporses, we only parseInt()+5
            ret = parseFloat(input) + 5;
            return ret;
        }

        function addTT(parentElement, arg1, arg2, arg3, arg4, arg5) {

            if (!arg1) {
                arg1 = "";
            }
            if (!arg2) {
                arg2 = "";
            }
            if (!arg3) {
                arg3 = "";
            }
            if (!arg4) {
                arg4 = "";
            }
            if (!arg5) {
                arg5 = num_format((0.00).toFixed(2));
            }


            row = $('<tr></tr>').attr('id', boxes);

            cell1 = $('<td class="inputcell"></td>');
            cell2 = $('<td class="inputcell"></td>');
            cell3 = $('<td class="inputcell"></td>');
            cell4 = $('<td class="inputcell"></td>');
            cell5 = $('<td class="inputcell"></td>');

            input1 = $('<input></input>').attr('style', 'width:100px;').attr('id', 'box' + boxes + '.1').attr('name', 'box' + boxes + '_1').attr('type', 'text').attr('value', arg1);
            input2 = $('<input></input>').attr('style', 'width:100px;').attr('id', 'box' + boxes + '.2').attr('name', 'box' + boxes + '_2').attr('type', 'text').attr('value', arg2);
            input3 = $('<input></input>').attr('style', 'width:93px;').attr('id', 'box' + boxes + '.3').attr('name', 'box' + boxes + '_3').attr('type', 'text').attr('value', arg3);
            input4 = $('<input></input>').attr('style', 'width:149px;').attr('id', 'box' + boxes + '.4').attr('name', 'box' + boxes + '_4').attr('type', 'text').attr('value', arg4);
            input5 = $('<input></input>').attr('style', 'width:90px;').attr('id', 'box' + boxes + '.5').attr('name', 'box' + boxes + '_5').attr('type', 'text').attr('value', arg5);

            $(cell1).append(input1);
            $(cell2).append(input2);
            $(cell3).append(input3);
            $(cell4).append(input4);
            $(cell5).append(input5);

            $(row).append(cell1);
            $(row).append(cell2);
            $(row).append(cell3);
            $(row).append(cell4);
            $(row).append(cell5);

            $('#tBoxes').append(row);
            boxes++;
        }

        function subTT(parentElement) {
            boxes = boxes - 1;
            $(parentElement + ' #' + boxes).hide(0, function () {
                $(parentElement + ' #' + boxes).remove();
            }
            );
        }
        function bindEmAll() {
            alert(boxes);
            for (var i = 1; i <= boxes - 1; i++) {

                $('#container input#box' + i + '\\.5').blur(function () {
                    alert($(this).val());
                    $(this).val(num_format($(this).val()));
                    //$('#container input#box' + i + '\\.5').val(num_format($('#container input#box' + i + '\\.5').val()));
                    //$('#Errorfield').append('Current box is $(\'#container input#box' + i + '\\.5\')<br />');
                });
            }
        }
        $('#addTT').click(function () {
            addTT('#container');
            bindEmAll();
        });
        $('#subTT').click(function () {
            subTT('#container');
        });
        $(function () { addTT('#container'); bindEmAll(); });

Here is a small example of adding new elements and process their events: 以下是添加新元素并处理其事件的一个小示例:

<button id="add">+</button>
<button id="remove">-</button>
<div id="holder">

</div>

.

$('#add').on('click', function () {
    $('#holder').append('<p>click me!</p>');
});

$('#remove').on('click', function () {
    $('#holder p:last-of-type').remove();
});

$('#holder').on('click', 'p', function () {
    alert('my id is: ' + $('#holder p').index(this));
});

And you can check it out here: http://jsfiddle.net/simo/PyKDz/ 你可以在这里查看: http//jsfiddle.net/simo/PyKDz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM