-1

我有以下 java 脚本片段

    <script>
    var editables = document.getElementsByClassName("canEdit");
    function editHandler(el) {
        return function() {
            window.alert(el.textContent);
        }
    }
    for (var i = 0; i < editables.length; i++) { 
        var el = editables[i];
        el.onclick = editHandler(editables[i]);
    }
    </script>

如果我注释掉该行,var el = editables[i];那么当我单击可编辑元素时不再弹出警报。为什么会这样?

4

2 回答 2

2

Why is this the case?

Because you used el to bind the event handler. If you comment out the line

var el = editables[i];

then the variable el won't exist and

el.onclick = editHandler(editables[i]);

will throw a reference error because you are trying to access the .onclick property of a non-existing variable. The event handlers are never bound.

You could use editables[i] instead:

editables[i].onclick = editHandler(editables[i]);
于 2013-06-27T00:03:58.047 回答
2

那条线定义了el. 没有它,就没有元素可以附加onclick处理程序。如果您在那里没有收到参考错误,则必须有一些(可能是全局的,如果您的代码片段是准确的)变量el已在您的代码中的其他地方定义。

于 2013-06-26T23:59:04.623 回答