简体   繁体   English

如何使用jQuery .each循环删除特定元素?

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

Assume I have an HTML document containing: 假设我有一个包含以下内容的HTML文档:

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

I want to get rid of the inputs values which satisfy some condition (given in my JS). 我想摆脱满足某些条件的输入值(在我的JS中给出)。 I have tried creating my removeGoodInputs() function (as below), but this removes all inputs from the form. 我已经尝试创建我的removeGoodInputs()函数(如下所示),但这将删除表单中的所有输入。 How can I resolve this issue? 我该如何解决这个问题?

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

attr is one the methods of jQuery object, you should first convert the DOM object this to a jQuery object and then use jQuery methods, $(this).attr("") , also you can use val method for getting/setting values of form controls instead of attr and you don't need each , you can use Attribute Equals Selector : 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']") selects the inputs that their values are 10 . $("#my_form input[value='10']")选择其值为10的输入。

Another way to solve this is to use .filter [docs] : 另一种解决方法是使用.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() is a jQuery method so it can only be called on a jQuery object. .attr()是一个jQuery方法,所以它只能在jQuery对象上调用。 Further, in jQuery .val() is the easier way to get the value (a shortcut). 此外,在jQuery中, .val()是获取值的更简单方法(快捷方式)。

So, this line of your code is not correct: 所以,这行代码不正确:

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

I would recommend either: 我会建议:

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

or: 要么:

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

Note, I also changed the comparisons to be strings since that is what .value returns and it's better to not rely on an automatic type conversion. 注意,我还将比较更改为字符串,因为这是.value返回的内容,最好不要依赖自动类型转换。

You can see it work here: http://jsfiddle.net/jfriend00/HMemp/ 你可以在这里看到它的工作: http//jsfiddle.net/jfriend00/HMemp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM