如何遍历表单jQuery的所有元素 [英] How to loop through all elements of a form jQuery
问题描述
我只是想知道遍历表单的所有子元素的最佳方法是什么? 我的表单同时包含input和select元素.
I was just wondering what the best way of looping through all the child elements of a form would be? My form contains both input and select elements.
目前,我有:
success: function(data) {
$.each(data.details, function(datakey, datavalue) {
$('#new_user_form > input').each(function(key, value) {
if($(this).attr('id') == datakey) {
$(this).val(datavalue);
}
});
});
}
尽管这只会循环通过表单的输入元素,我也想包括选择元素:
This only loops through the input elements of the form though and I want to include the select elements too:
我尝试过:
$('#new_user_form > input, #new_user_form > select').each(function(key, value) {
但这是行不通的.有谁知道为什么会这样? 谢谢!
but this doesn't work. Does anyone know why this would be happening? Thanks!
推荐答案
从jQuery :input选择器页面:
由于:input是jQuery扩展,而不是CSS规范的一部分,因此使用:input的查询无法利用本机DOM querySelectorAll()方法提供的性能提升.为了在使用:input选择元素时达到最佳性能,请首先使用纯CSS选择器选择元素,然后使用.filter(:input").
Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").
这是最好的选择.
$('#new_user_form *').filter(':input').each(function(){
//your code here
});
这篇关于如何遍历表单jQuery的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!