簡體   English   中英

如何使用jQuery .each循環刪除特定元素?

[英]How do I remove specific elements using an jQuery .each loop?

假設我有一個包含以下內容的HTML文檔:

<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();
    });
}

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的輸入。

另一種解決方法是使用.filter [docs]

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

.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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM