gpt4 book ai didi

javascript - 每次调用弹出窗口时,jQuery/js 都会存储/附加变量,但为什么呢?

转载 作者:行者123 更新时间:2023-11-30 12:33:27 25 4
gpt4 key购买 nike

我有一个弹出窗口,它在调用时获取一个变量 (userid),当我在弹出窗口中选择某些内容时,我将该变量赋予一个函数。

每次第一个变量都是新的,这是应该的。
但是第二个变量附加并包含上次调用弹出窗口时的所有值。

但是为什么以及如何防止呢?

JS代码:

$(".class").click(function() {
var userid = $(this).attr('id');
$(".popup").toggle();
console.log('first');
console.log(userid);

$(".popup td").click(userid,function() {
console.log('second');
console.log(userid);

$(".popup").hide();
});
});




控制台读数:

"first"
"1"
"second"
"1"

"first"
"2"
"second"
"1"
"2"

"first"
"3"
"second"
"1"
"2"
"3"

最佳答案

主要问题是每次点击 .class元素,您要为点击 .popup td 添加一个 事件处理程序元素。所以:

第一次点击:

"first""1""second""1"

Makes sense, the click output 1 and bound 1 to the handler it added, so clicking that .popup td shows 1 as well.

"first""2""second""1""2"

Also makes sense: You've clicked a second time (apparently on 2), so the .class handler shows 2 and binds a new event handler to the .popup td that will receive 2. Then when you click the .popup td element, it fires both of the handlers assigned to it (in the order they were assigned), so you see 1 followed by 2.

(And then the same sort of thing happens the third time, and so on, and so on...)

If your intention is to replace the handler, you can do that like this:

$(".class").click(function() {
var userid = $(this).attr('id');
$(".popup").toggle();
console.log('first');
console.log(userid);

$(".popup td").off("click.foo").on("click.foo", userid, function() {
console.log('second');
console.log(userid);

$(".popup").hide();
});
});

这会删除之前的所有 click.foo处理程序之前附加一个新的。

但是,我不会那样附加和分离处理程序。相反,只有 .class处理程序设置一个变量,即(一个).popup td处理程序可以使用:

var clickedUserId;                         // Declare it outside either handler
$(".class").click(function() {
clickedUserId = $(this).attr('id'); // Set it here
$(".popup").toggle();
console.log('first');
console.log(clickedUserId);
});
$(".popup td").click(function() {
console.log('second');
console.log(clickedUserId); // Use it here

$(".popup").hide();
});

只是为了完整性:我不会制作 clickedUserId a global,全局命名空间已经太拥挤了,只需在两个事件处理程序共享的范围内声明它即可。如果您还没有方便的作用域,请将上面的内容包装在一个立即调用的函数表达式 (IIFE) 中:

(function() {
var clickedUserId; // Declare it outside either handler
$(".class").click(function() {
clickedUserId = $(this).attr('id'); // Set it here
$(".popup").toggle();
console.log('first');
console.log(clickedUserId);
});
$(".popup td").click(function() {
console.log('second');
console.log(clickedUserId); // Use it here

$(".popup").hide();
});
})();

关于javascript - 每次调用弹出窗口时,jQuery/js 都会存储/附加变量,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26893623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com