![](/img/trans.png)
[英]How do I do a nested for-each loop with JQuery to get specific li elements?
[英]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();
});
}
另一種解決方法是使用.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.