繁体   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