3

嘿,我正在编写一个基本上添加事件侦听器的代码,该侦听器使用其 dom 对象的 id 的片段调用一个函数,但是每次我用侦听器单击一个对象时,无论我单击什么对象,它都会给我相同的值这是我的代码

//add events
for (a=0; a<=tab_array.length-3; a++)
{
alert(a);
document.getElementById("mini_"+a).addEventListener("click",function(){open_tab(a)},false); 
}


function open_tab(e)
{
//change across settings ect
alert("tab "+e+" clicked");
}

我意识到它可能与指针有关,事实上它使用匿名函数而不是直接传递 a,但我只是不知道该怎么做

4

2 回答 2

2

你的猜测是正确的。您看到的行为是因为您的范围。

当您的链接被点击时,javascript 正在传递a.
此值tab_array.length-2代替a循环运行期间的值0, 1 ...

为了保持值,a您必须在新范围(闭包)中创建一个新变量。例如e

for (a=0; a<=tab_array.length-3; a++)
{
  function(e){
    document.getElementById("mini_"+e).addEventListener("click",function(){open_tab(e)},false); 
  }(a));
}

另一种方法是编写一个函数,在它自己的范围内返回你的处理程序:

//add events
for (a=0; a<=tab_array.length-3; a++)
{
  alert(a);
  document.getElementById("mini_"+a).addEventListener("click", open_tab(a) ,false); 
}

function open_tab(e) {
  return function() {
    //change across settings ect
    alert("tab "+e+" clicked");
  }
}

my fiddleClosure guide

于 2013-07-14T07:42:10.990 回答
0

Both of @jantimon's code samples are fine ways to solve this problem, but I'd like to suggest a third approach. Instead of a self-calling function expression or a function that returns a function, consider an ordinary named function:

for( var i = 0;  i <= tab_array.length - 3;  ++i ) {
    setupTab( i );
}

function setupTab( i ) {
    var element = document.getElementById( 'mini_' + i );
    element.addEventListener( 'click', function() {
        open_tab( i );
    }); 
}

This is essentially the same code as the self-calling function, but with these advantages:

  1. Familiarity. It's just an ordinary function call.
  2. Shorter and simpler loop body.
  3. With the self-calling function, the function parameter and the actual argument passed in are at opposite ends of the function (parameter at the beginning, argument at the end). A separate function avoids that.

These are just minor advantages, to be sure—any of these approaches will do the trick. But I do like the clarity of this method.

于 2013-07-14T09:07:06.133 回答