【问题标题】:Why Does This Index Number Seem to Work Even Though the Index is Closed?为什么即使索引已关闭,此索引号似乎也有效?
【发布时间】:2016-04-08 14:01:16
【问题描述】:

这个问题与我之前在Using Mouseenter / MouseLeave to Change Div in JavaScript 提出的问题有关。

正如回答的那样,我遇到了索引关闭问题。我有一个使用现有索引的新函数,并且提供的答案非常有意义 - 除了一个部分。

之后:

for (var i = 0; i < radialDivList.length; i++) {
    if (!radialDivList[i]) continue; //skip null, undefined and non-existent elements
    if (!radialDivList.hasOwnProperty(i)) continue; //skip inherited properties
    smallID[i] = radialDivList[i].id; //assign the list of four divs to the smallID array;
    largeID[i] = smallID[i] + 'Full'; // add "Full" to each smallID element to make a largeID element
}

我有

$('#' + smallID[i]).mouseenter(function () { //works for all four radial menu divs when mouse enters
    alert(largeID[i]); // undefined
    alert(largeID); // gives expected output of full array

我现在明白为什么 largeID 索引未定义,但我不明白为什么 mouseenter 函数适用于所有四个径向菜单项。我对索引闭包的理解使我认为 smallID[i].mouseenter 函数的 [i] 的值将是“3”,给定前一个 for 循环的结果。如果是这样,为什么所有四个菜单部分都正确触发了 mouseenter 事件?

感谢您愿意提供的任何帮助!

@programmerGuy - 想进一步解释上一个问题吗?

【问题讨论】:

  • 除非我们能看到所有引用变量的完整内容以及它们的定义位置和方式,否则无法回答此类问题。这就是闭包的本质。
  • 你在for循环中绑定了mouseenter,对吧?如果是,那么您发布了不相关的代码。如果没有,请提供简单的 MCVE 复制问题
  • @hogan 我很抱歉。我认为问题的具体性质将使代码片段能够提供足够的信息。原始代码已被替换,但我会将其从 Git 中拉出并重新发布。感谢您抽出宝贵时间回复!

标签: javascript jquery arrays indexing closures


【解决方案1】:

这似乎与浏览器缓存问题有关。重启后,此代码不再触发 mouseenter 事件。

【讨论】:

    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 2019-10-25
    • 2023-03-14
    • 2012-01-24
    • 2018-10-09
    • 2011-07-08
    • 2018-05-26
    • 2011-04-13
    相关资源
    最近更新 更多