jsLint错误的问题:“不要在循环内做功能” [英] Question on jsLint error: "Don't make functions within a loop"

查看:97
本文介绍了jsLint错误的问题:“不要在循环内做功能”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


  1. 在代码示例中我会得到一个错误,表示不要在循环中的功能。

  2. 当我尝试修复它,我似乎失去了这个的范围

  3. 我需要看一个如何解决这个错误的例子。

  4. 这是jsfiddle: http://jsfiddle.net/pkdsleeper/ejvMj/

感谢提前



睡眠者

解决方案

这样做就可以在循环中定义本地函数:

 (function highlightRows(){

use strict;

if(!document.getElementById ||!document.getElementsByTagName){return false;}

function handleMouseOver(){
this.style.backgroundColor =crimson;
this.style.color =#ffffff;
}

函数handleMouseOut(){
this.style.backgroundColor =transparent;
this.style.color =#000000;
}


var tbl = document.getElementById(tbl_example),//获取表
rows = tbl.getElementsByTagName(tr),/ /得到所有的表行
i,
current_row;

//循环通过行向mouseover / mouseout事件添加样式信息
for(i = 0; i< rows.length; i ++){
current_row = rows [一世];

//取消第th行的亮点
if(current_row.parentNode.tagName ===THEAD){
continue;
}

current_row.onmouseover = handleMouseOver;
current_row.onmouseout = handleMouseOut;
}
}())

在jsFiddle中工作: http://jsfiddle.net/jfriend00/aKfWs/


I'm reading DOM 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/.

这篇关于jsLint错误的问题:“不要在循环内做功能”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆