jQuery-我不应该重复选择器(存储在变量中)吗? [英] Jquery - Should I not repeat selectors (store in a variable)?

查看:96
本文介绍了jQuery-我不应该重复选择器(存储在变量中)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些时候,我发现自己重复了几次选择器.我应该以某种方式将一个jquery对象存储到一个变量中,然后只使用那个对象吗?举个简单的例子,该怎么办?

There are some times when I find myself repeating a selector several times. Should I be somehow storing a jquery object to a variable and then just using that one? As a quick example, what about the following?:

$('a.contactus').css('padding', '10px');
$('a.contactus').css('margin', '4px');
$('a.contactus').css('display', 'block');

现在我知道这不是一个很好的例子,因为实际上您可以只链接每个CSS函数.但是,假设在这两个条件之间是有条件的语句或阻止您链接的内容.

Now I know this isn't a great example, since effectively you could just chain each css function. But suppose in between each of those was a conditional statement or something to stop you from chaining.

我可以将jquery对象存储在变量中吗?如果是这样,我什么时候应该可以?

Can I store a jquery object in a variable? And if so, when should I / can I?

推荐答案

您可以这样做

var myvar = $('a.contactus');
myvar.css('padding', '10px').css('margin', '4px').css('display', 'block');

但出于可读性考虑,我这样做

but for readability i do this

var myvar = $('a.contactus');
myvar.css('padding', '10px')
  .css('margin', '4px')
  .css('display', 'block');

基本上,每次您使用$(someselector)时,您都会遍历dom.如果可以的话,应该存储元素引用.

basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference.

这篇关于jQuery-我不应该重复选择器(存储在变量中)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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