JavaScript 删除所有隐藏元素,但只有一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7871388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:35:53  来源:igfitidea点击:

JavaScript to remove all hidden elements but one

javascriptjquery

提问by user

Someone helped me find JavaScript code to remove hidden form fields from submissionand code that ignores a certain fieldthat I don't want removed (whether it's hidden or not):

有人帮我找到了从提交中删除隐藏表单字段的JavaScript代码忽略我不想删除的某个字段的代码(无论它是否隐藏):

$("form").submit(function() {
$(this).find(":hidden").remove(); // hide hidden elements before submitting
});

and

:not(input[name=csrfmiddlewaretoken])

However, I can't for the life of me figure out how to put these together. I'm sure it's a basic JavaScript question, but I can't seem to piece these together.

但是,我终其一生都无法弄清楚如何将这些组合在一起。我确定这是一个基本的 JavaScript 问题,但我似乎无法将它们拼凑在一起。

Does anyone know how to remove all hidden form entries not namedcsrfmiddlewaretoken? If you do, I'd really appreciate it.

有谁知道如何删除所有未命名的隐藏表单条目csrfmiddlewaretoken?如果你这样做,我真的很感激。

Thanks a lot.

非常感谢。

回答by qwertymk

$(this).find(":hidden").not('input[name=csrfmiddlewaretoken]').remove();

Or

或者

$(this).find(":hidden").filter(':not(input[name=csrfmiddlewaretoken])').remove();

Or

或者

$(this).find("input[name!=csrfmiddlewaretoken]:hidden").remove();

回答by Ankur

$(this).find(":hidden").filter("[name!='csrfmiddlewaretoken']").remove();

回答by Wyatt

You can pass the thisas a context argument, which will be potentially faster than making a jQuery object from it. The :not()expression can follow the :hiddenwithout spaces, meaning that it adds a second condition to the :hiddenselector.

您可以将 传递this为上下文参数,这可能比从中创建 jQuery 对象更快。的:not()表达可以按照:hidden没有空格,这意味着它增加了一个第二条件的:hidden选择器。

$(":hidden:not(input[name=csrfmiddlewaretoken])", this).remove();