jQuery Duplicate Selector error

巧了我就是萌 提交于 2019-11-30 06:14:32
aebmad

There is no such a Duplicated jQuery Selector error; that's a warning thrown by IntelliJ (and other IDEs from idea like WebStorm...) suggesting that you should store your jQuery selection in a local variable rather than repeating the selection.

Excerpt from jQuery documentation:

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.

However, in your code there is no duplicated jQuery selection so I bet that warning is coming from somewhere else.. What is in line with the fact that the error persists after adding the missing $.

In general is a good practice to add the reported error to your questions..

The "duplicate selector" is indeed a JS lint warning, that you'll see in IDEs like PHPStorm / WebStorm. For performance reasons, you'll want to cache your selectors whenever possible.. e.g.:

(function($) {
  var 
    $mondayCommentLink = $("#mondayCommentLink"),
    $mondayHtmls = $("#mondayComment"),
    $inputMonday = $("<input type='text' id='mondayCommentText' name='mondayCommentText'  />");

    $mondayCommentLink.on('click', function() {
      $inputMonday.val(data.days[0].comment);
      $mondayHtmls.html($inputMonday);
    });

})(jQuery);

.. and so on. I just did Monday, but you'd continue to add a variable reference to the selector that you can grab that's already in memory. Things are a bit more complicated when dealing with AJAX or if you have multiple scopes, but this is the basic idea. It's just convention, but I find it easier to reference selectors with var $elem and camelcased.

ojonugwa ochalifu

I had this same error trying something like this:

if  ($("#checkbox").is(':checked')){
   value = $("#checkbox").val();

For some reason, the error was thrown on "#checkbox". I solved the problem by including:

//noinspection JSJQueryEfficiency at the top of the if statement like this:

 //noinspection JSJQueryEfficiency
 if  ($("#checkbox").is(':checked')){
   value = $("#checkbox").val();

and the error message went away.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!