使用 jQuery 在 onchange 中循环输入项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/424932/
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-08-26 09:07:31  来源:igfitidea点击:

Loop through input items onchange with jQuery

jquery

提问by Chris Bartow

When a select field is changed, I would like to loop through all of the input values in the form it belongs to using jQuery. This doesn't work below, but I can't figure out exactly how to do this.

更改选择字段时,我想使用 jQuery 遍历它所属表单中的所有输入值。这在下面不起作用,但我无法弄清楚如何做到这一点。

$("select.mod").change(function(){
    $(this).parent().get(0).$(":input").each(function(i){
    alert(this.name + " = " + i);
  });
});

回答by Steve Losh

It's probably the selection of the "parent form" that's causing the problem.

这可能是导致问题的“父表单”的选择。

The .parent()function returns just the immediate parent, which won't let you get the form element if your select.modis nested in a <p>or something.

.parent()函数仅返回直接父级,如果您select.mod嵌套在 a<p>或其他内容中,则不会让您获得表单元素。

The .parents()function returns allthe parents of the element; but the first one might not be the form tag. I'd try this:

.parents()函数返回元素的所有父元素;但第一个可能不是表单标签。我会试试这个:

$("select.mod").change(function(){
    $(this).parents('form') // For each element, pick the ancestor that's a form tag.
           .find(':input') // Find all the input elements under those.
           .each(function(i) {
        alert(this.name + " = " + i);
    });
});

That still might not help you if you have form elements nested inside each other, but if that's the case you've probably got bigger problems than a jQuery selector...

如果您的表单元素相互嵌套,那仍然可能无济于事,但如果是这种情况,您可能会遇到比 jQuery 选择器更大的问题......

回答by rfunduk

Your problem is almost certainly:

你的问题几乎肯定是:

.$(":input")

That doesn't make sense. You're trying to call the $(":input")method on whatever .get(0)returns... of course there is no such method!

那没有意义。您试图$(":input")在任何.get(0)返回时调用该方法......当然没有这样的方法!

What you're looking for is probably more like:

您正在寻找的可能更像是:

$(this).parent().find(":input").each( ... )

Could offer more help with more details. Getting an error? What's the DOM structure? Etc.

可以提供更多详细信息的更多帮助。出现错误?什么是 DOM 结构?等等。

Personally, I usually have id's on my forms. So I'd make things clea(r|n)er like:

就个人而言,id我的表格上通常有's。所以我会让事情变得清晰(r|n):

$('#my_awesome_form :input').each( ... )