2012-09-09 1310 views
0

假設我有一個包含一個HTML文檔:如何使用jQuery .each循環刪除特定元素?

<form id = "my_form"> 
    <input type = "text" /> 
    <input type = "text" /> 
    <input type = "text" /> 
    <button type = "button" onclick = "removeGoodInputs()">Do the job</button> 
</form> 

我想擺脫它滿足一定條件的輸入值(在我的JS給出)。我試圖創建removeGoodInputs()函數(如下所示),但是這會刪除表單中的所有輸入。我該如何解決這個問題?

function removeGoodInputs() { 
    $("#my_form input").each(function() { 
     if(this.attr("value") == 10) 
      $(this).remove(); 
    }); 
} 

回答

0

.attr()是一個jQuery方法,因此可以僅一個jQuery對象上被調用。此外,在jQuery .val()是獲取值(一個快捷方式)的更簡單的方法。

所以,這行代碼是不正確的:

if(this.attr("value") == 10) 

我會建議之一:

if (this.value == "10")  // plain javascript 

或:

if ($(this).val() == "10") // jQuery 

注意,我也改變了比較成爲字符串,因爲這是什麼.value回報,最好不要依賴自動類型轉換。

你可以看到它在這裏工作:http://jsfiddle.net/jfriend00/HMemp/

+0

此外,它可以'如果($(本).attr( 「值」) == 10)' –

+0

@SheikhHeera - 是的,這是一個選項,但當'.val()'或'.value'更直接時,沒有必要這樣做。 – jfriend00

+0

是的,我同意,只是評論,因爲你用這種方式回答它,所以我認爲它應該作爲另一種選擇提及。 –

0
function removeGoodInputs() { 
$("#my_form input").each(function() { 
    if($(this).val() == 10) $(this).remove(); 
}); 
} 
1

attr是jQuery對象的一個​​方法,你應該先DOM對象this轉換爲一個jQuery對象,然後使用jQuery方法,$(this).attr(""),也可以使用val方法來獲得/設置值形式的控制,而不是attr和你不需要each,你可以使用Attribute Equals Selector

function removeGoodInputs() { 
    $("#my_form input[value='10']").remove(); 
} 

$("#my_form input[value='10']")選擇它們的值爲10的輸入。

1

另一種方式來解決這個問題是使用.filter[docs]

$("#my_form input").filter(function() { 
    return this.value === '10'; 
}).remove(); 
相關問題