开发者

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

I'm reading DOM开发者_JS百科 Scripting by Jeremy Keith and testing the code in jsLint

  1. In the code sample here it i'm getting an error that says ""Don't make functions within a loop".
  2. When I try to fix it, I seem to be losing the scope of this
  3. I need to see an example of how to fix this error.
  4. Here is the jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/

Thanks In Advance

sleeper


One way to do it is like this where you define local functions outside the loop:

(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;
    }    
}())

Working in a jsFiddle: http://jsfiddle.net/jfriend00/aKfWs/.


maybe something like this:

var initMouseover = function() {
    return function () {
        this.style.backgroundColor = "crimson";
        this.style.color = "#ffffff";
    };
};

and then in for loop you have:

current_row.onmouseover = initMouseover();

I test it on link you post and it seems to work and also doesn't show this error anymore.


Your code seems to work fine as is. The this inside your event handler functions refers to the DOM object that fired the event, which is a <tr> element. Thus you can change your styles by modifying the properties of this. You can access the same object via a function parameter as well.

current_row.onmouseover = function (event) {
            console.log(this == event.currentTarget);
}

That will log true to the console because this and event.currentTarget are the same DOM element object.

But yes, you are correct in that in the scope of your for loop, this (which you don't use in that exact scope) is the top level window object, but within the event handler functions, this is a different object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜