关于jsLint错误的问题:“Don't make functions within a loop”
Question on jsLint error: "Don't make functions within a loop"
我正在阅读Jeremy Keith的DOM Scripting并在jsLint中测试代码
- 在这里的代码样本中,我得到一个错误,说"不要在一个循环内做函数"。
- 当我试图修复它时,我似乎正在失去这个 的范围
- 我需要看看如何修复这个错误的例子。
- 这是jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/
Thanks In Advance
睡眠这样做的一种方法是在循环外定义局部函数:
(function highlightRows() {
"use strict";
if (!document.getElementById || !document.getElementsByTagName) { return false; }
function handleMouseOver () {
this.style.backgroundColor = "crimson";
this.style.color = "#ffffff";
}
function handleMouseOut() {
this.style.backgroundColor = "transparent";
this.style.color = "#000000";
}
var tbl = document.getElementById("tbl_example"), // get the table
rows = tbl.getElementsByTagName("tr"), // get all the table rows
i,
current_row;
// loop through rows adding style info to the mouseover/mouseout events
for (i = 0; i < rows.length; i++) {
current_row = rows[i];
// cancel highlight of th row
if (current_row.parentNode.tagName === "THEAD") {
continue;
}
current_row.onmouseover = handleMouseOver;
current_row.onmouseout = handleMouseOut;
}
}())
在jsFiddle中工作:http://jsfiddle.net/jfriend00/aKfWs/.
可以这样写:
var initMouseover = function() {
return function () {
this.style.backgroundColor = "crimson";
this.style.color = "#ffffff";
};
};
然后在for循环中有:
current_row.onmouseover = initMouseover();
我测试了你的链接,它似乎工作,也没有显示这个错误了。
您的代码似乎工作得很好。事件处理程序函数中的this
指向触发事件的DOM对象,这是一个<tr>
元素。因此你可以通过修改this
的属性来改变你的样式。您也可以通过函数形参访问相同的对象。
current_row.onmouseover = function (event) {
console.log(this == event.currentTarget);
}
这将把true
记录到控制台,因为this
和event.currentTarget
是相同的DOM元素对象。
但是,是的,你是正确的,在你的for
循环的范围内,this
(你没有在那个确切的范围内使用)是顶级window
对象,但在事件处理程序函数中,this
是一个不同的对象。
相关文章:
- PHP and Javascript functions
- JavaScript onTap functions
- jquery ajax success functions not executing
- Make:如果父元素溢出,after元素将扩展到全宽
- 使用wp_enque_script()在Wordpress-functions.php中添加Javascript
- Is it good to make function in function using 'return
- HTML javascript functions
- history.pushState in Chrome make favicon request
- 如何绕过绑定的Javascript OnChange Functions
- Node.js assert.throws with async functions (Promises)
- Javascript - make 函数在函数完成时告诉调用者
- 如果 Functions 是 javascript 中的对象,为什么 function.constructor 指向 F
- Javascript Functions
- jquery ajaxform global functions
- Javascript Functions for Node.js
- jQuery AJAX IE - skipped functions ajax
- Javascript Funky Functions
- AngularJS ng-src async functions
- how to make a <div> appear in slow motion
- 关于jsLint错误的问题:“Don't make functions within a loop”