0

我无法将数组的值放入动态创建的元素上添加的事件的函数调用中。

所以这里是工作得很好的硬编码版本:

var parent_item = document.getElementById("developers_container");

var part = document.createElement('div');
part.id = "developer_A";
part.name = "developer_A";
part.className = "developer_block_un";
part.onmouseover = function() { hilight_dev('A',true)};
part.onmouseout = function() { hilight_dev('A',false)};
parent_item.appendChild(part);

var parent_item = document.getElementById("developer_A");

var part = document.createElement('span');
part.id = "developer_title_A";
part.name = "developer_title_A";
part.className = "developer_un";
part.innerHTML = "John Doe";
part.onclick = function() { select_dev('A')};
parent_item.appendChild(part);

基本上,它的作用是创建一个供选择的用户列表。每个用户的列表都有 mouseover、mouseoff 和 onclick 事件。目前正在为每个用户复制上述代码的内容。

我想用基于数组的函数替换重复项:

var dev_id = new Array();
var dev_fn = new Array();
var dev_ln = new Array();

document.getElementById("developers_container").innerHTML = "";

dev_id[0] = "A";
dev_fn[0] = "John";
dev_ln[0] = "Doe";

dev_id[1] = "B";
dev_fn[1] = "John";
dev_ln[1] = "Smith";

dev_id[2] = "C";
dev_fn[2] = "John";
dev_ln[2] = "Jones";

dev_id[3] = "D";
dev_fn[3] = "John";
dev_ln[3] = "Yougetthepoint";

document.getElementById("developers_container").innerHTML = "";

for(var i = 0; i < dev_id.length; i++) 
{
    var parent_item = document.getElementById("developers_container");

    var part = document.createElement('div');
    part.id = "developer_"+dev_id[i];
    part.name = "developer_"+dev_id[i];
    part.className = "developer_block_un";
    part.onmouseover = function() { hilight_dev(dev_id[i],true)};
    part.onmouseout = function() { hilight_dev(dev_id[i],false)};
    parent_item.appendChild(part);

    var parent_item = document.getElementById("developer_"+dev_id[i]);

    var part = document.createElement('span');
    part.id = "developer_title_"+dev_id[i];
    part.name = "developer_title_"+dev_id[i];
    part.className = "developer_un";
    part.innerHTML = dev_fn[i]+"<BR>"+dev_ln[i];
    part.onclick = function() { select_dev(dev_id[i])};
    parent_item.appendChild(part);
}

除了添加的事件之外,每一点都工作得很好。在函数代码中使用“dev_id[i]”的地方(如“part.onmouseover = function() { hilight_dev(dev_id[i],true)};”),它似乎没有做任何事情。事件触发并调用函数,但传递的变量是“未定义”,而不是应有的用户 ID。

我希望这里有人知道如何让它工作。谷歌搜索不是很有帮助,这是我花了半天时间试图弄清楚的那些愚蠢的小问题之一。非常感谢任何和所有帮助。

谢谢

4

1 回答 1

1

part.onmouseover = function(i) { 
  return function() { hilight_dev(dev_id[i],true) }
}(i)

在调用函数时,循环中的变量 i 未定义,您需要在其上形成一个闭包以保持其值。请参阅 Douglas Crockford 的“JavaScript, the Good Parts” 以获得关于此的详细解释

Err.. 在 Neil 的评论之后.. 是的.. i 不是未定义的.. 它始终是 dev_id 的长度.. 无论如何,这不是操作想要的:)

于 2013-01-30T21:31:35.567 回答