gpt4 book ai didi

Javascript 函数覆盖自身

转载 作者:行者123 更新时间:2023-11-28 13:23:15 25 4
gpt4 key购买 nike

抱歉,标题不太清楚,我不太确定问题是什么。如果有人有更好的主意,我会很乐意重命名它。

我有一堆带有“something-box”类的盒子,通过单击我给定“something-button”类的各种东西来调用它们。所有的盒子也有一个“模态框”类,并且所有的盒子都包含在一个部分透明的 div 中,该 div 覆盖了屏幕的其余部分(“模态遮光”)。我没有为每个按钮编写完全相同的代码(我正在这样做),而是决定创建一个函数将相关的单击处理程序附加到每个按钮(以及伴随它的其他各种东西)。我有以下 js 代码:

    function modal(selector) {
button = $(selector+'-button');
box = $(selector+'-box');
button.click(function(e) {
e.stopPropagation();
$('.modal-box').hide();
$(document).off('.hideDoc');
$('.modal-blackout').show();
box.show();
$(document).on('click.hideDoc', function(e) {

if (!box.is(e.target) && box.has(e.target).length === 0)
{
$('.modal-blackout').hide();
box.hide();
$(selector + '-box .error-message').html('');
$(document).off('.hideDoc');
}
});
e.preventDefault();
});
}

modal('.password-reset');
modal('.login');
modal('.signup');

但现在每个按钮都会弹出 .signup-box(或最后调用的那个)。请注意,如果我删除该函数并使用代码中各处的不同选择器手动将其写出三次,它就会按我的预期工作。

怀疑这里有一些我不明白的基本内容。谁能解释一下吗?

最佳答案

您正在创建每次调用 modal() 时都会覆盖的全局变量。这会导致 box 始终引用最后一个选择器选择的框,与 button 类似。

对于按钮,这并不是真正的问题,因为您只使用它一次。但是,对 box 的引用必须保持准确,因为它在 click 事件处理程序中使用。

替换:

function modal(selector) {
button = $(selector+'-button');
box = $(selector+'-box');

与:

function modal(selector) {
var button = $(selector+'-button');
var box = $(selector+'-box');

这将导致这些变量在 modal 的范围内创建,因此对 modal 的后续调用无法覆盖为先前选择器设置的变量。

关于Javascript 函数覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403409/

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