Mar
23
2009

การใช้งาน jQuery ร่วมกับ Other Libraries

เนื่องจาก JavaScript Library (jQuery, Prototype, MooTools, YUI or etc.) ต่างก็มี shortcut function คือ $-function เหมือนกัน จะทำอย่างไรละครับทีนี้ถ้าเราจะใช้ Libraries อื่นๆ ร่วมกับ jQuery

1. กรณีที่ โหลดตัว jQuery ตามหลัง Other Libraries
กรณีนี้เราจะต้อง overriding $-function โดยการเรียก jQuery.noConflict() และตำแหน่งที่เรียก jQuery.noConflict() จะนำไปไว้ตรงไหนก็ได้แต่จะต้องวางไว้หลัง jQuery และ Other Libraries ทำการโหลด
ส่วน shortcut function ของ jQuery คุณสามารถใช้ jQuery แทน $ และ shortcut function ของ Other Libraries ก็ให้ใช้ $ เหมือนเดิม
ตัวอย่าง 1.1

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

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

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


ตัวอย่าง 1.2

<html>
<head>
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script type="text/javascript">
     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. กรณีที่ โหลดตัว jQuery ก่อน Other Libraries
กรณีนี้ไม่ต้อง overriding $-function โดยการเรียก jQuery.noConflict()
ส่วน shortcut function ของ jQuery และ shortcut function ของ Other Libraries ก็ให้ใช้เหมือนกรณีแรก
ตัวอย่าง

<html>
<head>
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script type="text/javascript">
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });

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

Comments are closed.