2015-09-04 76 views
0

我有以下的代碼,它工作正常:jQuery的 - 用同一類中選擇元素,功能只有

$(function() { 
    $('select').on('change', function(event){ // This binds listeners to the change event on all the select elements 
     var sId = this.id; // store off the changed element id 
     var vId = this.value; // store off the changed element value 
     var nId = this.name; // store off the changed element name 
     alert(sId + nId + vId); // for testing 
     $('select').each(function(){ // this loops across the same set of elements 
      if(this.name != nId && this.value == vId) { // If it is not the triggering element and the value is the same, do something 
       this.options.selectedIndex = 0; // reset the value to 'rank' 
      } 
     }); 
    }); 
}); 

此代碼對頁面上的所有下拉菜單 - 我試圖做的是限於只有類dropdown_1的下拉菜單 - 這可能嗎?

+1

所以使用選擇你想要的元素選擇。 https://api.jquery.com/class-selector/ – epascarello

回答

2

你可以改變selectdropdown_1代碼,如: -

$(function() { 
    $('.dropdown_1').on('change', function (event) { // This binds listeners to the change event on all the select elements 
     var sId = this.id; // store off the changed element id 
     var vId = this.value; // store off the changed element value 
     var nId = this.name; // store off the changed element name 
     alert(sId + nId + vId); // for testing 
     $('.dropdown_1').each(function() { // this loops across the same set of elements 
      if (this.name != nId && this.value == vId) { // If it is not the triggering element and the value is the same, do something 
       this.options.selectedIndex = 0; // reset the value to 'rank' 
      } 
     }); 
    }); 
}); 
+0

奇怪的是,我已經嘗試過了,它不起作用 - 會再試一次。 –

+0

@Homer_J好的,沒問題。如果你仍然面臨這個問題,只需創建一個功能性示例來說明[jsFiddle](http://jsfiddle.net/)上的問題。我會仔細看看的。 –

+0

沒有像人類錯誤@palash ....幫助如果'所有'我需要被稱爲'dopdown_1'的選擇選項實際上被稱爲dropdown_1 ...排序和工作 - 謝謝。 –

相關問題