简体   繁体   中英

How to resolve jQuery conflict?

I have a jQuery custom file which is disabling or conflicting my other jQuery file, please how do i resolve this. Please see below: My Custom file:

$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

Conflicting Files:

<script src="js/jquery.isotope.min.js"></script>
<script src="js/nprogress.js"></script>

I would be more than happy if this is resolved.

I'm assuming that you know for certain jQuery is conflicting - you've checked the console errors, etc.

You could wrap your jQuery in a self-executing anonymous function as follows:

(function($) { 
  $(".search").keyup(function() 
  { 
  var searchid = $(this).val();
  var dataString = 'search='+ searchid;
  if(searchid!='')
  {
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
       {
         $("#result").html(html).show();
       }
     });
   }return false;    
  });
})(jQuery);

EDIT - a bit of explanation of what's happened above. In order to prevent any potential conflicts with other scripts / frameworks we are passing the jQuery object as an argument to our function (hence function($) ). The benefits of doing this is that you can now use $ locally within the function at will. Without fear of conflicting with other scripts on a global scope.

I Was able to fix the problem by just wrapping it with:

$(document).ready(function() {  
//-----
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM