繁体   English   中英

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

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

所以我正在研究这个问题,我需要生成元素,然后将事件绑定到它们。 每次我生成一个元素时,我解除绑定并用for循环将事件重新绑定到生成的元素。 这些函数似乎触发了,但它们得到了错误的索引(它告诉代码使用哪个元素)。

查看jsFiddle http://jsfiddle.net/6UgYe/4/上的代码

解决这个问题的任何模块化都可以。 也可以随意评论我的代码。 我刚刚开始使用javascript时写了大部分内容。

问候,

Akke

编辑:这是行动的解决方案: http//jsfiddle.net/nwH8Z/3/它计算模糊的增值税免费价格。

bindEmAll函数更改为如下所示 -

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

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

})
}

它使所有带有以“.5”结尾的ID的输入框将其由num_format()函数处理的id和值附加到#Errorfield 事件处理程序附加到#container 所有输入框,即使它们是动态添加的。

并删除bindEmAll()从你的点击处理程序#addTT ; 否则事件处理程序将被绑定多次,因为你点击addTT,这使得事情相当混乱;-)

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

这里更新了小提琴。

问题正在发生,因为blur事件处理程序直到循环结束后才运行。 执行顺序是:

  • 将事件处理程序附加到项目1上的模糊事件
  • 附加事件处理程序以模糊第2项上的事件

...一段时间之后...

  • 实际上调用模糊事件

在调用事件处理程序时,循环中变量i的值已更改为最后一个值的索引,因此这是事件处理程序中使用的值。

要解决这个问题,您可以将代码置于闭包中:

 (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);

我在这里更新了你的小提琴

  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(); });

以下是添加新元素并处理其事件的一个小示例:

<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));
});

你可以在这里查看: http//jsfiddle.net/simo/PyKDz/

暂无
暂无

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

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