2011-11-14 61 views
8

我正在处理一些复杂的形式。在此选择所有输入,标签,选择等 - 每个循环

只是想知道,有没有更好的方式来做到这一点:

$('.selector').each(function(){ 

    $("input", this).prop('disabled', true); 
    $("select", this).prop('disabled', true); 
    $("label", this).prop('disabled', true); 
    $("textarea", this).prop('disabled', true); 

}); 

我想内this(目前通过.selector循环)选择全部输入。 我是否正确地做这件事?

+1

是的,在技术上。虽然下面的@ BoltClock的答案是这样做的更好的方法。 – rossipedia

回答

16

这很好,但为了简化它,你应该能够使用逗号,你会到组中的任何其他选择:

$('.selector').each(function() { 
    $('input, select, label, textarea', this).prop('disabled', true); 
}); 

如果你正在做的唯一事情是设置在那些元素属性,那么你并不需要.each()循环。您可以放心地将其减少并将其减少到这一行:

$('input, select, label, textarea', '.selector').prop('disabled', true); 
+0

'$(“。selector input,.selector select,.selector label,.selector textarea”)。prop('disabled',true);'equivalent? –

+0

@Brian M. Hunt:应该是。此外,'$('。selector')。find('input,select,label,textarea')。prop('disabled',true);' – BoltClock

+0

整洁。我想知道他们之间是否有任何性能差异。 –