内的jQuery点击事件 [英] JQuery click event inside for

查看:80
本文介绍了内的jQuery点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道发生了什么事..

I really don´t know what is happening to me..

代码类似于:

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    $tourButton.click(function() {
        alert(name);
    }
}

我试图将每个显示事件名称的按钮的单击事件绑定在一起,但是无论单击哪个按钮,它始终显示最后一个游览名称.

I´m trying to bind the click event for each button which displays the tours name, but is always displaying the last tour name whichever the button I'm clicking.

我在做什么错了?

谢谢!

推荐答案

在for循环继续进行之前,您需要将点击处理程序包装在闭包中,以封闭"变量name的值.

You need to wrap the click handler in a closure to 'close-over' the value of the variable name before the for-loop moves on.

这是因为直到您单击处理程序才真正执行该处理程序,因此否则它将仅使用当时name的当前值(无论循环中的最后一个值是什么).

This is because the handler isn't actually executed until you click on it, so otherwise it will simply use the current value of name at that time (whatever the last value in the loop was).

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    (function(n) {
        $tourButton.click(function() {
            alert(n);
        });
    })(name)
}

这篇关于内的jQuery点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆