关于JavaScript的函数中重复调用同一个Id选择器问题

不管是JavaScript还是jQuery中,基本选择器的种类只有id选择器、name选择器、class选择器、标签选择器几种,调用语法无非是id前加#、class前加.、直接写标签名等;

我们通常的用法都只是一个id选择器对应一个方法或事件,实际上也就是同一个id选择器只使用一次;因为id属性的唯一性,也就导致了id选择器的理论上唯一性,但并非真的唯一。

实际开发中,同一个id选择器使用多次的情况不在少数,有些IDE就会对这种使用方法产生黄色警告问题

意思就是:jQuery选择器出现多次;因为多次调用了这个id选择器,所以产生了这种问题,当然也不影响编译和运行,但是对于强迫症来说,真的好烦人!!!

解决方法: 

下面是官方文档给出的解释:

Saving Selections

jQuery doesn't cache elements for you. If you've made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.

1| var divs = $( "div" );

Once the selection is stored in a variable, you can call jQuery methods on the variable just like you would have called them on the original selection.

A selection only fetches the elements that are on the page at the time the selection is made. If elements are added to the page later, you'll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don't magically update when the DOM changes.

意思就是,当我们在函数中多次调用同一个选择器时,我们应该使用一个变量来存储这个选择器( save the selection in a variable),而不是每次使用时都去调用一下( rather than making the selection repeatedly.),因为JQuery不会为你缓存元素(jQuery doesn't cache elements for you);

所以当我们确定要多次调用同一个id选择器时,我们应该这样来定义:

var divs = $( "div" );

其实就是用变量来存储了一下这个id标签,为下一次调用做准备,提高了系统运行的效率性能等。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值