是否可以在 jQuery 中使用多个变量而不是选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3576592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use multiple variables instead of selectors in jQuery
提问by Gabriel
I know that it's faster to do the following:
我知道执行以下操作会更快:
var $header = $("#header");
$header.css({color:"#ff0000"});
$header.find("a").addClass("foo");
Instead of:
代替:
$("#header").css({color:"#ff0000"});
$("#header a").addClass("foo");
Because jQuery doesn't need to find the elements again in the DOM as we have direct reference to them.
因为 jQuery 不需要在 DOM 中再次查找元素,因为我们可以直接引用它们。
Let's say that I have this:
假设我有这个:
var $header_elements = $("#header li");
var $footer_elements = $("#footer li");
And I use both individually for a few jQuery manipulations. But then, I need to do something on both. Using selector, I would do this:
我将两者单独用于一些 jQuery 操作。但是,我需要对两者都做些什么。使用选择器,我会这样做:
$("#header li, #footer li").css({color:"#ff0000"});
But then, the DOM needs to be parsed again to find matching elements. Is there a way to use my previously declared variables instead of a new selector? Something like the following (which is notworking, I know, it's to give an idea of what I'm looking for):
但是,需要再次解析 DOM 以找到匹配的元素。有没有办法使用我之前声明的变量而不是新的选择器?类似于以下内容(我知道这是行不通的,这是为了让我了解我在寻找什么):
$($header_elements + $footer_elements).css({color:"#ff0000"});
I think that the selector returns some kind of array or object. What I'm looking for is a way to merge those. Anyone know if this is possible and how to do it?
我认为选择器返回某种数组或对象。我正在寻找的是一种合并这些的方法。任何人都知道这是否可能以及如何做到这一点?
Thanks for your help!
谢谢你的帮助!
回答by djdd87
Just use the add
method:
只需使用以下add
方法:
$header_elements.add($footer_elements).css({color:'#ff0000'});
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
给定一个表示一组 DOM 元素的 jQuery 对象,.add() 方法根据这些元素和传递给方法的元素的联合构造一个新的 jQuery 对象。.add() 的参数几乎可以是 $() 接受的任何内容,包括 jQuery 选择器表达式、对 DOM 元素的引用或 HTML 片段。
回答by Gabriel
I found the solutions a few minutes after posting this. For those who are wondering, here it is:
发布后几分钟我找到了解决方案。对于那些想知道的人,这里是:
$.merge($header_elements, $footer_elements).css({color:"#ff0000"});
Is it faster? I don't know yet, I'll need to run some tests to find out.
它更快吗?我还不知道,我需要进行一些测试才能找到答案。
EDIT:
编辑:
I tested it with JS Fiddle here : http://jsfiddle.net/bgLfz/1/
我在这里用 JS Fiddle 进行了测试:http: //jsfiddle.net/bgLfz/1/
I tested using selector each time, variable for both selector, variables with $.merge() and using .add(). Each test was run 1000 times.
我每次都使用选择器进行测试,两个选择器的变量,带有 $.merge() 的变量和使用 .add() 的变量。每个测试运行 1000 次。
Results on my side are as follow (from faster to slower):
我这边的结果如下(从快到慢):
- Using $.merge() (average of 7ms)
- Using both variable one after the other (average of 10ms but the code needs to be duplicated)
- Using .add() (average of 16ms)
- Using selectors each time (average of 295ms)
- 使用 $.merge()(平均 7ms)
- 一个接一个地使用这两个变量(平均 10ms 但代码需要复制)
- 使用 .add()(平均 16ms)
- 每次使用选择器(平均 295ms)
回答by Simon Arnold
You can use add
or merge
method:
Add
$header_elements.add($footer_elements).css({color:'#f00'});
merge
合并
$.merge($header_elements, $footer_elements).css({color:"#f00"});
Both work, but add is more performant.
Source:http://jsperf.com/add-vs-merge
两者都有效,但add 的性能更高。
来源:http : //jsperf.com/add-vs-merge
Credit:I upvoted @GenericTypeTea and @Gabriel answers, did a summary of both, compared them and here is the result.
信用:我赞成@GenericTypeTea 和@Gabriel 的答案,对两者进行了总结,比较了它们,这是结果。
回答by Anpher
Pass an array of references:
传递引用数组:
$([$header_elements, $footer_elements]).css({color:"#ff0000"});
回答by raveren
It does not matter performance wise wether you'll do something like (even if it worked):
您是否会执行以下操作(即使它有效)在性能方面并不重要:
$($header_elements + $footer_elements).css({color:"#ff0000"});
or do them separately:
或者分开做:
$($header_elements).css({color:"#ff0000"});
$($footer_elements).css({color:"#ff0000"});
as jquery will internally go through the supplied arguments using each()
.
因为 jquery 将在内部使用each()
.
If the principle is more DRY
inspired, than performance wise, you can create a function:
如果原理更DRY
受启发,而不是性能方面,您可以创建一个函数:
function makeThemRed( el ) {el.css({color:"#ff0000"})}
and then
进而
makeThemRed($header_elements);
makeThemRed($footer_elements);
or even:
甚至:
function makeThemRed()
{
var l=arguments.length,
o=0;
while (o<l) {
arguments[o++].css({color:"#ff0000"})
}
}
and then
进而
makeThemRed($header_elements, $footer_elements); //any number of parameters
回答by Hazem_M
The thing with using 'merge' is that it's limited to just two selectors, and using 'add' will be so messy if it's more than two, so if it's more than two, you should use 'each' like this:
使用 'merge' 的问题是它仅限于两个选择器,如果它超过两个,使用 'add' 会很混乱,所以如果它超过两个,你应该像这样使用 'each':
$([selector1, selector2, selector3, .....etc]).each(function(){
// your code here
});
回答by Lasithds
To keep the code simple and prevent code duplicationI used a forEach
loop.
为了保持代码简单并防止代码重复,我使用了一个forEach
循环。
var $header_items = $("#header li");
var $footer_items = $("#footer li");
[$header_items, $footer_items].forEach(function($blockItems){
// do logic here
$blockItems.css('color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
<h1>Header</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
<div id="footer">
<h1>Footer</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
回答by Brian Ray
You could always set all of the elements to one variable:
您始终可以将所有元素设置为一个变量:
var $lis = $('#header li, #footer li');
$($lis).css({color:"#ff0000"});
回答by kwyjibear
Use ES6 template literals for multiple variables as selectors:
对多个变量使用 ES6 模板文字作为选择器:
$(`${$header_elements}, ${$footer_elements}`).css('color','#ff0000');