在使用phpstorm/Intellj的编辑器写jQuery代码时,经常提示Duplicated jQuery selector警告,如下图:


  原因是由于在同一个函数中,多次使用jQuery调用同一元素,浪费资源。解决的办法为声明一个变量,让这个变量存储这个选择器,如下图:

如此问题解决。

官方原文:

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.

谷歌翻译:

保存选择

jQuery不会为您缓存元素。 如果您已经做出了可能需要再次进行的选择,则应将选择保存在变量中,而不是重复进行选择。

1| var divs = $(“div”);

一旦选择存储在变量中,您就可以在变量上调用jQuery方法,就像在原始选择上调用它们一样。

选择仅在选择时获取页面上的元素。 如果稍后将元素添加到页面中,则必须重复选择或以其他方式将它们添加到存储在变量中的选择。 当DOM更改时,存储的选择不会神奇地更新。

发表评论

必填项已用*标注