2015-11-22 40 views
-1

下面的代碼將刪除我的編輯表單中的所有選項。但是在刪除選項後,我想添加一個默認選項。我試過下面的代碼,但也.add和.prepend我找不到正確的代碼。我究竟做錯了什麼?嘗試向選擇列表添加選項

$("#editform").find("select").each(function(){ 
       alert(this.id); 
       this.options.length = 0; 
       this.append($('<option/>', { value: '', text : 'Selecteer' })); 
      }); 
+0

取代''由$(本)'this'。 –

回答

0

如果您檢查了console.log,您可能會看到類似Uncaught TypeError: this.append is not a function的錯誤。 Append是一個jQuery函數,因此您需要使用jQuery構造函數。將this更改爲$(this)。即:

$("#editform").find("select").each(function(){ 
    alert(this.id); 
    this.options.length = 0; 
    $(this).append($('<option/>', { value: '', text : 'Selecteer' })); 
}); 
+0

是this.options.length = 0;也不正確呢? –

+0

否。在這種情況下,'this'是指找到的對象(在本例中是select元素)。你很好地在每個範圍內使用'this'。如果您使用'$(this)',它將使用jQuery來嘗試並執行不存在的.options()方法。 – Jordan

0
append is jquery function: 
$("#editform").find("select").each(function(){ 
      alert(this.id); 
      this.options.length = 0; 
      $(this).append($('<option/>', { value: '', text : 'Selecteer' })); 
     }); 
+0

只有代碼的答案永遠不會像答案一樣好,如果不是一些伴隨的文本解釋,評論。 - [審查期間](http://stackoverflow.com/review/low-quality-posts/10297448)。 –

+0

追加是jquery函數,當使用[this]意味着使用javascript而不是jquery,並且在這種情況下[this]沒有函數稱爲append –

相關問題