2013-08-31 132 views
0

此代碼將傳遞由循環創建的最後一個值eventListener函數,我需要在創建eventListener時附加值。Javascript在循環中將參數傳遞給eventListener函數

window.onload = function() { 

var el = document.getElementsByClassName('modify'); 

for (var i = 0; i < el.length; i++) { 

    var getId=el[i].id.split("_"); 

    document.getElementById("modify_y_"+getId[2]).addEventListener('mouseover', function() { 
    document.getElementById("modify_x_"+getId[2]).style.borderBottom = '#e6665 solid 3px'; 
    }, false); 

} 
} 
+1

很常見的問題,這裏是一個解釋:http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example –

+0

@MattGreer:使用閉包是多年來的最佳實踐,但是我們應該開始教人們使用'bind',因爲它是一種優秀的解決方案,並且很快將被內置到所有人們瞄準的瀏覽器中 –

+0

@MartinJespersen酷,我沒有意識到你可以通過參數綁定。由於我們支持舊的IE,我仍然沒有使用過它。感謝您的高舉。 –

回答

1

可以使用bind原型所存在的所有功能在現代瀏覽器

window.onload = function() { 

var el = document.getElementsByClassName('modify'); 

for (var i = 0; i < el.length; i++) { 

    var getId=el[i].id.split("_"); 

    document.getElementById("modify_y_"+getId[2]).addEventListener('mouseover', function(theid) { 
     document.getElementById("modify_x_"+getId[2]).style.borderBottom = '#e6665 solid 3px'; 
    }.bind(null,getId[2]), false); 

} 
} 

如果您需要支持沒有bind nativly建在舊的瀏覽器,你可以使用這個poly-fill taken from MDN在那裏你會還對綁定的原型功能找到文檔

if (!Function.prototype.bind) { 
    Function.prototype.bind = function (oThis) { 
    if (typeof this !== "function") { 
     // closest thing possible to the ECMAScript 5 internal IsCallable function 
     throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 
    } 

    var aArgs = Array.prototype.slice.call(arguments, 1), 
     fToBind = this, 
     fNOP = function() {}, 
     fBound = function() { 
      return fToBind.apply(this instanceof fNOP && oThis 
           ? this 
           : oThis, 
           aArgs.concat(Array.prototype.slice.call(arguments))); 
     }; 

    fNOP.prototype = this.prototype; 
    fBound.prototype = new fNOP(); 

    return fBound; 
    }; 
} 
+0

什麼是順便說一句,第一個參數爲空? – user1209203

+0

第一個參數設置函數的''''''值' - 因爲您不需要特定的'this'我將其設置爲空 - 閱讀提供的文檔鏈接以充分理解函數 –

1

你這樣做,通過使用設計器功能:

window.onload = function() { 

    var el = document.getElementsByClassName('modify'); 

    for (var i = 0; i < el.length; i++) { 

     var getId = el[i].id.split("_"); 

     document.getElementById("modify_y_" + getId[2]).addEventListener('mouseover', makeHandler(getId[2]), false); 

    } 

    function makeHandler(theId) { 
     return function() { 
      document.getElementById("modify_x_" + theId).style.borderBottom = '#e6665 solid 3px'; 
     }; 
    } 
}; 

通過makeHandler返回的功能關閉在theId的說法,這不會改變。