Event doesn't get added in a for-loop

前端 未结 3 423
清酒与你
清酒与你 2020-12-22 10:38

This is the html. If a link is clicked I want to replace the span-element in front of it with some text.

that1

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-22 11:13

    The problem with your original code is that you're creating a closure on the variable n. When the event handler is called, it is called with the value of n at the point of invocation, not the point of declaration. You can see this by adding an alert call:

    $(document).ready(function() {
        var numSpans = $("span").length;
        for (n = 1; n <= numSpans; n++) {
            $("a#update" + n).click(function(e) {
                alert(n); //Alerts '6'
                $('span#sp' + n).replaceWith('this');
                e.preventDefault();
            });
        }
    })
    

    One way to fix this is to create a closure on the value of n in each iteration, like so:

    $(document).ready(function() {
        var numSpans = $("span").length;
        for (n = 1; n <= numSpans; n++) {
            $("a#update" + n).click(
                (function(k) {
                    return function(e) {
                        alert(k);
                        $('span#sp' + k).replaceWith('this');
                        e.preventDefault();
                    }
                })(n)
            );
        }
    })
    

    However, this is messy, and you'd do better to use a more jQuery-y method.


    One way to do this would be to remove the ids from your code. Unless you need them for something else, they're not required:

    that1 Update1

    that2 Update2

    that3 Update3

    that4 Update4

    that5 Update5

    jQuery:

    $(function() {
        $('a.update').live('click', function() {
            $(this).siblings('span').replaceWith("Updated that!");
        });
    });
    

    jsFiddle

提交回复
热议问题