![](/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.