我遇到一些相当简单的香草Javascript的麻烦。它所做的只是通过标签名称获取所有p元素,并为每个元素附加一个事件处理程序,它调用一个将颜色更改为红色的函数。
回调函数el
之外引用了正确的元素1-6。但是在循环内部,它总是引用最后一个,尽管javascript的词汇变量范围性质。为什么这样做,以及可以采取哪些措施来实施入侵行为?
小提琴:https://jsfiddle.net/7j4bg68g/
<p>1 This is a test.</p>
<p>2 This is a test.</p>
<p>3 This is a test.</p>
<p>4 This is a test.</p>
<p>5 This is a test.</p>
<p>6 This is a test.</p>
...
function takeAction() {
this.style.color = 'red';
}
var els = document.getElementsByTagName('p');
for (var i = 0; i < els.length; i++) {
var el = els[i];
// logs els 1 to 6 as expected.
console.log(el.innerHTML);
el.addEventListener('click', function() {
// logs "6 This is a test.", and makes the last <p> tag red,
// regardless of which <p> element you click on.
console.log(el.innerHTML);
takeAction.call(el);
}, false);
}
答案 0 :(得分:1)
这是因为关闭,在您的代码中,您引用了&#34; el&#34;。所有事件处理程序都引用了相同的变量el,它已更改为循环中给出的最后一个值。 试试这个,
function takeAction() {
this.style.color = 'red';
}
var els = document.getElementsByTagName('p');
for (var i = 0; i < els.length; i++) {
var el = els[i];
// logs els 1 to 6 as expected.
console.log(el.innerHTML);
(function(elem){
elem.addEventListener('click', function() {
// logs "6 This is a test.", and makes the last <p> tag red, regardless of which <p> element you click on.
console.log(elem.innerHTML); // logs "6 This is a test."
takeAction.call(elem);
}, false);
})(el);
}