是否可以使用多个变量而不是jQuery中的选择器 [英] Is it possible to use multiple variables instead of selectors in jQuery

查看:49
本文介绍了是否可以使用多个变量而不是jQuery中的选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道执行以下操作会更快:

I know that it's faster to do the following:

var $header = $("#header");
$header.css({color:"#ff0000"});
$header.find("a").addClass("foo");

代替:

$("#header").css({color:"#ff0000"});
$("#header a").addClass("foo");

因为jQuery无需在DOM中再次找到元素,因为我们直接引用了它们.

Because jQuery doesn't need to find the elements again in the DOM as we have direct reference to them.

让我说这个:

var $header_elements = $("#header li");
var $footer_elements = $("#footer li");

我分别将它们用于一些jQuery操作.但是然后,我需要对两者都做一些事情.使用选择器,我会这样做:

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:

$("#header li, #footer li").css({color:"#ff0000"});

但是,随后需要再次解析DOM以找到匹配的元素.有没有办法使用我之前声明的变量而不是新的选择器?类似于以下内容(不起作用,我知道这是为了让我对所要查找的东西有所了解):

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 not working, I know, it's to give an idea of what I'm looking for):

$($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?

感谢您的帮助!

推荐答案

只需使用 add 方法:

Just use the add method:

$header_elements.add($footer_elements).css({color:'#ff0000'});

给出一个表示以下内容的jQuery对象 一组DOM元素.add() 方法构造一个新的jQuery对象 从这些元素的结合中 那些传入方法.这 .add()的参数可能很多 $()接受的任何内容,包括 jQuery选择器表达式,引用 DOM元素或HTML代码段.

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.

这篇关于是否可以使用多个变量而不是jQuery中的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆