Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当您知道只有一个匹配元素时,是否应该始终使用jQuery first()方法?_Javascript_Jquery_Performance - Fatal编程技术网

Javascript 当您知道只有一个匹配元素时,是否应该始终使用jQuery first()方法?

Javascript 当您知道只有一个匹配元素时,是否应该始终使用jQuery first()方法?,javascript,jquery,performance,Javascript,Jquery,Performance,当您试图在jQuery中选择一个元素,并且知道只有一个元素时,出于性能原因使用first()方法还是不使用它更好 例如: $('#myForm').children('input[name=some_field]'); VS: 在这种情况下,在jquery中使用.length if($('#myForm').children('input[name=some_field]').length) 不,不是“有益的”。。。first()方法仅适用于DOM数组元素 :第一个选择器可能更适合短路搜索

当您试图在jQuery中选择一个元素,并且知道只有一个元素时,出于性能原因使用
first()
方法还是不使用它更好

例如:

$('#myForm').children('input[name=some_field]');
VS:


在这种情况下,在jquery中使用
.length

if($('#myForm').children('input[name=some_field]').length)
不,不是“有益的”。。。
first()
方法仅适用于DOM数组元素


:第一个
选择器可能更适合短路搜索

$('#myElement').children('input[name=some_field]:first')

如果它只是其中一个,并且您知道id,请使用id。否则,您的输入

// Get the value from a dropdown select

$( "select.foo option:selected").val();

// Get the value from a dropdown select even easier
$( "select.foo" ).val();

// Get the value from a checked checkbox

$( "input:checkbox:checked" ).val();

// Get the value from a set of radio buttons

$( "input:radio[name=bar]:checked" ).val();

即使您不需要这些值,这也是访问这些元素的一种方式。仅举几个直接访问它而不是从父元素访问它的示例

如果您确定无需麻烦,我认为。如果只有一个元素,.first()不做任何事情(除了无意义地调用函数),函数将按顺序执行。如果您先添加
。则添加了另一个函数。为什么这会提高性能?@Stryner哦,好的,谢谢。我认为一旦找到第一个元素,它可能会停止寻找更多的元素;但我想即使有更多,它仍然会找到所有的,但只返回第一个?@Brett确实如此。如果您输入了[name=some_field]:首先,它可能会提高性能,但即使这样也不能保证。
// Get the value from a dropdown select

$( "select.foo option:selected").val();

// Get the value from a dropdown select even easier
$( "select.foo" ).val();

// Get the value from a checked checkbox

$( "input:checkbox:checked" ).val();

// Get the value from a set of radio buttons

$( "input:radio[name=bar]:checked" ).val();