使用jQuery循环输入项onchange

Chr*_*tow 3 jquery

更改选择字段时,我想使用jQuery以它所属的形式循环遍历所有输入值.这在下面不起作用,但我无法弄清楚具体如何做到这一点.

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

Ste*_*osh 9

这可能是导致问题的"父母形式"的选择.

.parent()函数只返回直接父级,如果你select.mod的嵌套在一个<p>或者某个东西中,它将不会让你获得表单元素.

.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);
    });
});
Run Code Online (Sandbox Code Playgroud)

如果你有相互嵌套的表单元素,这仍然可能没有帮助,但如果是这种情况你可能比jQuery选择器有更大的问题...