的問題是,你的elem
總是指向最後select
元素。最簡單的辦法是在處理程序使用this
代替ELEM變量http://jsfiddle.net/mendesjuan/aRMpt/140/
function loaded(){
var selectElems=document.getElementsByName("select");
for(i=0;i<selectElems.length;i++){
var elem=selectElems[i];
elem.onchange=function(){
// This points to the select element that was changed
alert(this.selectedIndex);
}
}
}
這並沒有真正告訴你,你的問題是什麼,但。這是一個解決方法(雖然很好)。您的代碼不起作用的原因是您的關閉功能onchange
與關閉使用相同的elem
。在您撥打onchange
時,elem
指向最後一個select
元素。爲了避免這種情況的方法是引入另一封是凍結的ELEM您onChange處理http://jsfiddle.net/mendesjuan/aRMpt/142/
function loaded(){
var selectElems=document.getElementsByName("select");
for(i=0;i<selectElems.length;i++){
var elem=selectElems[i];
// Freeze the elem variable by creating a function that passes
// the elem and creates a separate closure for each handler
elem.onchange= (function(el) {
// This is the function that will actually be the handler
return function(){
// This points to the select element that was changed
alert(el.selectedIndex);
}
}) (elem)
}
這裏是另外一個例子,可以幫助你理解上面的例子是如何工作的。
// This is a function that returns another function
// Its only reason is so that we don't use the shared closure
// variables from the outer scope, it freezes the el
// variable at the moment its called and so that it's available
// when the handler is called
function createOnChangeHandler(el) {
return function() {
alert(el.selectedIndex);
}
}
function loaded(){
var selectElems=document.getElementsByName("select");
for(i=0;i<selectElems.length;i++){
var elem=selectElems[i];
// If we just use elem here, its value will be what it was assigned last
// in the loop. That is because the handler won't be called until
// this loop has finished. However, by calling another function,
// a new scope is created with the value that we're passing into it
elem.onchange = createOnChangeHandler(elem);
}
的變量中的此凍結也可以通過使用Function.bind來完成,但在新的瀏覽器這僅適用;但是,上面的鏈接顯示瞭如何使其不適用於瀏覽器。 http://jsfiddle.net/mendesjuan/aRMpt/143/
function loaded(){
var selectElems=document.getElementsByName("select");
for(i=0;i<selectElems.length;i++){
var elem = selectElems[i];
elem.onchange = (function (el) {
alert("Select index: " + el.selectedIndex)
}).bind(null, el);
}
我認爲每一個JS開發之前已經過這個問題上運行。我會確保你理解第二個解決方案,因爲你將來可能需要它(例如,如果你想使用'i'變量)。但對於這種情況,我只會使用第一個。 – 2012-02-08 23:40:33
說實話,我是javascript的新手,特別是你的第二個例子有點難以理解,現在我用google搜索....如果你知道關於這個例子的任何好教程你能指點我 – 2012-02-08 23:50:21
增加了一些關於它如何工作的評論。隨意提問,不用擔心,消化需要一些時間,但在理解它之前,你無法真正稱自己爲一名優秀的JS開發人員。 – 2012-02-09 00:23:32