JQuery警告:Duplicated jQuery selector

本文探讨了在使用jQuery时如何避免重复使用相同的选择器来提高代码执行效率。通过将选择器结果存储到变量中,可以减少不必要的DOM操作,进而提升网页性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.如果你在一个函数中重复写这个id的选择器,你就可能遇到这种警告,而这种警告通常实在Intellj系列的编辑器中显示,警告截图如下:




上面代码中两处使用了同一个id选择器,JQuery建议你使用一个变量去存储这个选择器,而不是每次用的时候便拿来调用一下,它不会帮你做缓存,而是重新去取。可以参考StackOverflow上的回答:https://stackoverflow.com/questions/16863844/jquery-duplicate-selector-error



官方文档说明:http://learn.jquery.com/using-jquery-core/selecting-elements/#saving-selections

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.



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值