Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - Using JQuery and Prototype in the same page

Several of my pages use both JQuery and Protoype. Since I upgraded to version 1.3 of JQuery this appears to be causing problems, because both libraries define a function named '$'.

JQuery provides a function noConflict() which relinquishes control of $ to other libraries that may be using it. So it seems like I need to go through all my pages that look like this:

<head>      
    <script type="text/javascript" src="/obp/js/prototype.js"></script>
    <script type="text/javascript" src="/obp/js/jquery.js"></script>
</head>

and change them to look like this:

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

I should then be able to use '$' for Prototype and '$j' (or 'jQuery') for JQuery. I'm not entirely happy about duplicating these 2 lines of code in every relevant page, and expect that at some point somebody is likely to forget to add them to a new page. I'd prefer to be able to do the following

  • Create a file jquery-noconflict.js which "includes" jquery.js and the 2 lines of code shown above
  • Import jquery-noconflict.js (instead of jquery.js) in all my JSP/HTML pages

However, I'm not sure if it's possible to include one JS file in another, in the manner I've described? Of course an alternate solution is simply to add the 2 lines of code above to jquery.js directly, but if I do that I'll need to remember to do it every time I upgrade JQuery.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Currently you can do something like this:

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

Then, use jQuery as $j() and Prototype's $().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...