2016-08-03 42 views
1

我在页面中有多个表单。我只需要获取提交表单的输入子项。Jquery:获取仅提交表单的输入

这是我的代码(当然它不起作用)。

$('form.modal-form').on('submit',function(e) { 
     e.preventDefault(); 
     var form_errors = 0; 
     $(this).children('input.required-field').each(function(index) 
     { 
      [....] 
    }); 
}); 

非常感谢您

+0

哪里是你的HTML吗?什么是错误? – springrolls

回答

1

您可以选择context的元素。这是jQuery函数的选择器之后的第二个参数。在那里传递this让jQuery的搜索您的选择仅在此context,它会给你只是你正在寻找...元素

$('form.modal-form').on('submit', function(e) { 
    e.preventDefault(); 

    $('input.required-field', this).each(function() { 
     // do your work 
    }); 
}); 

你使用children可能不会在这里工作,因为这种功能只会搜索一个节点深入您的选择器。您可以从.children()切换到.find(),该做什么工作。

但我仍然希望使用上下文选择器!

+0

谢谢。它的工作;) – sineverba

+0

不客气,@sineverba! – eisbehr

2

您需要使用$.fn.find,而不是$.fn.children,只得到直接孩子:

$(this).find('input.required-field').each(function(index) { 
    // ... 
}); 
+0

它的工作原理,谢谢! – sineverba

+0

顺便说一句,'$(this).find('input.required-field')'相当于'$('input.required-field',this)'所以选择你更喜欢的任何东西。 – dfsq

+0

@eisbehr嗯,这是在这种情况下发生的事情:https://github.com/jquery/jquery/blob/305f193aa57014dc7d8fa0739a3fefd47166cd44/src/core/init.js#L94 – dfsq