jQuery -prototype conflict

半城伤御伤魂 提交于 2019-12-04 05:04:38

问题


I am using a combination of prototype and script.aculo.us to implement a lightbox effect in my asp.net page.I have also jquery included in my page.I have several DIV tags in my page,But after including the prototype file in my head of the page,I am not able to read the divs in my javascript using jquery

var div = $("#divLeftSideModelsList"); 
alert(div)

gives me an error saying that the object is null But

var div = document.getElementById("divLeftSideModelsList")

is giving me the object.

Is this becuase there is some conflicts between jQuery and other frameworks ?

PLEASE advice


回答1:


Have a read of this: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Shows good examples :)

OVERRIDING THE $-FUNCTION

However, you can override that default by calling jQuery.noConflict() at any point after jQuery and the other library have both loaded. For example:

 <html>
 <head>
   <script src="prototype.js"></script>
   <script src="jquery.js"></script>
   <script>
     jQuery.noConflict();

     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });

     // Use Prototype with $(...), etc.
     $('someid').hide();
   </script>
 </head>
 <body></body>
 </html>

This will revert $ back to its original library. You'll still be able to use "jQuery" in the rest of your application.

Additionally, there's another option. If you want to make sure that jQuery won't conflict with another library - but you want the benefit of a short name, you could do something like this:

 <html>
 <head>
   <script src="prototype.js"></script>
   <script src="jquery.js"></script>
   <script>
     var $j = jQuery.noConflict();

     // Use jQuery via $j(...)
     $j(document).ready(function(){
       $j("div").hide();
     });

     // Use Prototype with $(...), etc.
     $('someid').hide();
   </script>
 </head>
 <body></body>
 </html>



回答2:


You should use jQuery in noConflict mode. And then use jQuery() instead of $().




回答3:


Strange bug. Anyways, both prototype and jQuery redefine the global variable $.

Please read this to know how jQuery can play nice with other libraries.

It basically says that calling jQuery.noConflict() leaves the $ variable alone for the other libs to use




回答4:


Does this code work:

var div = jQuery("#divLeftSideModelsList");
alert(div);


来源:https://stackoverflow.com/questions/971106/jquery-prototype-conflict

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