1

I have an array of list items in a piece of Javascript code. I would like to assign an onclick event handler to each one. Each handler would be the same function, but with a different input argument. Right now I have:

function contentfill(i) {
    box = document.getElementById("text");
    box.style.background="rgba(0,0,0,0.8)";
    var content = new Array();
    contentdivs = document.querySelectorAll("#contentfill>div");
    box.innerHTML = contentdivs[i].innerHTML;
}
li[3].onclick = function() {contentfill(0);};
li[4].onclick = function() {contentfill(1);};
li[5].onclick = function() {contentfill(2);};

This works well enough, but I would like to achieve the same thing with a loop, for example:

for(i=3;i<=5;i++) {
    j=i-3;
    li[i].onclick = function() {contentfill(j);};
}

This, however, does not work. Since j seems to be defined as 2 at the end of the loop, each time I click, it only seems to call contentfill(2).

4

2 回答 2

3

对于另一种方法,请考虑让每个元素都知道它应该使用什么参数。

for (var i = 0; i < 3; i++) {
    var el = li[i + 3];
    el.dataset.contentIndex = i;
    el.addEventListener('click', contentfill);
}

当然,然后contentfill必须从中提取论点.dataset而不是进行论点。(这与 jQuery 的机制相同$.data。)

我更喜欢这个,因为(a)它不会生成大量微小的包装,(b)它允许我稍后检查并可能更改“参数”,并且(c)它允许我在文档中使用data-属性预定义它们. 有效地将它们从函数参数更改为行为。

于 2013-01-15T02:19:00.550 回答
1

的值i - 3应该绑定到点击处理函数;闭包可以提供此功能:

li[i].onclick = (function(j) {
    return function() {
        contentfill(j);
    }
)(i - 3));

addEventListener顺便说一句,使用或attachEvent注册点击处理程序是更好的做法。

于 2013-01-15T01:52:29.053 回答