Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery.each循环删除特定元素?_Javascript_Jquery_Dom_Each - Fatal编程技术网

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

Javascript 如何使用jQuery.each循环删除特定元素?,javascript,jquery,dom,each,Javascript,Jquery,Dom,Each,假设我有一个HTML文档,其中包含: <form id = "my_form"> <input type = "text" /> <input type = "text" /> <input type = "text" /> <button type = "button" onclick = "removeGoodInputs()">Do the job</button> </form&

假设我有一个HTML文档,其中包含:

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

attr
是jQuery对象的方法之一,您应该首先将DOM对象
this
转换为jQuery对象,然后使用jQuery方法,
$(this).attr(“”
),也可以使用
val
方法来获取/设置表单控件的值,而不是
attr
,并且您不需要
每个
,您可以使用
属性等于选择器

function removeGoodInputs() {
    $("#my_form input[value='10']").remove();
}
$(“#我的表单输入[value='10'])
选择其值为
10
的输入

.attr()
是一个jQuery方法,因此只能对jQuery对象调用它。此外,在jQuery中,
.val()
是获取值的更简单方法(快捷方式)

因此,这行代码不正确:

if(this.attr("value") == 10)
我建议:

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

注意,我还将比较更改为字符串,因为
.value
返回的是字符串,最好不要依赖自动类型转换


您可以在此处看到它的工作原理:

解决此问题的另一种方法是使用:


如果($(this).attr(“value”)==10)
@sheikheera-是的,这是一个选项,但是当
.val()
.value
更直接时,这样做没有意义。是的,我同意,只是因为你用
或者
的方式回答了这个问题,所以我认为应该把它作为另一个选项提出来。是的,错误来了,因为那不是我的代码的确切示例,只是想把关键行带到这里。无论如何,问题实际上是我在if指令中构造条件的方式。不过,谢谢你的帮助:D@user1658414-因此,您的问题没有准确显示问题的原因?
if(this.attr("value") == 10)
if (this.value == "10")      // plain javascript
if ($(this).val() == "10")   // jQuery
$("#my_form input").filter(function() {
    return this.value === '10';
}).remove();