关于jsLint错误的问题:“Don't make functions within a loop”

Question on jsLint error: "Don't make functions within a loop"

本文关键字:make functions within loop 错误 jsLint 问题 Don 关于      更新时间:2023-09-26

我正在阅读Jeremy Keith的DOM Scripting并在jsLint中测试代码

  1. 在这里的代码样本中,我得到一个错误,说"不要在一个循环内做函数"。
  2. 当我试图修复它时,我似乎正在失去这个
  3. 的范围
  4. 我需要看看如何修复这个错误的例子。
  5. 这是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记录到控制台,因为thisevent.currentTarget是相同的DOM元素对象。

但是,是的,你是正确的,在你的for循环的范围内,this(你没有在那个确切的范围内使用)是顶级window对象,但在事件处理程序函数中,this是一个不同的对象。