jQuery循环选择的最佳方法

jquery optimal method of selecting in loop

本文关键字:最佳 方法 选择 循环 jQuery      更新时间:2023-09-26

我编写一个从表单收集输入的函数。但是有很多方法可以选择输入。我环顾四周,根据以下方法找不到具体的答案。

是否可以像在

jquery 选择器中那样向 find() 添加多个选择(以防我需要收集输入和下拉列表)?

哪个是最佳的,为什么?

还有其他选择吗?

jQuery

//method 1: Id selector
var formId = $('.modal.fade.in').find('form').attr('id');
$('#' +formId+ ' input').each(function(input)
{
     //gather values
}
//method 2: Object and find
var form = $('.modal.fade.in').find('form');
$(form).find('input').each(function(input)
{
     //gather values
}

只需创建一个更大的选择器:

$('#' +formId+ ' input, #' + formId + ' select').each(function(element)
{
 //gather values from inputs and selects
}

我会做这样的事情:

var v = {};
$('#' +formId).find('select, input, textarea'). each(function (){
var tmp;
if($(this).attr('type') == 'checkbox' || $(this).attr('radio') == 'checkbox')
{
   tmp = $(this).is(':checked')?1:0;
}elseif($(this).attr('type') == 'submit'){
   return;
}else{
   tmp = $(this).val();
}
v[$(this).attr('id')] = tmp;
});