jQuery と prototype.js のコンフリクト(競合)について
Google Maps API では jQuery を使用する。
こちらのGoogle Mapsのページ のGoogleマップの表示で、ハマったのは、jQuery と prototype.js のコンフリクト(競合)。
このページでは、下位バージョンのIEで表示したときに「
IE6 No More」を表示すようにしており、「
IE6 No More」を表示するのに prototype.js を使用している。
その prototype.js が、jQuery とコンフリクト(競合)し、Googleマップ がきちんと動作しなかった。
jQuery日本語リファレンス
Prototype JavaScript framework: a foundation for ambitious web applications
jQuery と prototype.js のコンフリクト(競合)の対処法。
3つの対策をした。
- 「$」をjQuery として動作するようにする。
- 「$」を「document.getElementById」に。
- for-in文 ではなく for文で。
「$」をjQuery として動作するようにする。
jQueryの「noConflict」を使う(下記のサンプルの5行目)。
「$」は prototype.js でも、jQuery でも使われ、競合してしまう。
jQuery では「$」は、様々な要素に使われる。
prototype.js では「$」は、「document.getElementById」の代わりに使われる。
下記のサンプルの7行目「// この中では「$」は jQuery として動作。」の箇所に、Google Maps のコードを入れた。
【サンプル】
1 2 3 4 5 6 7 8 9 10 | <script type= "text/javascript" src= "js/prototype.js" ></script>
<script type= "text/javascript" src= "js/jquery.js" ></script>
<script><!--
jQuery.noConflict();
jQuery(document).ready( function ($){
});
--></script>
|
※6行目の「jQuery(document).ready(function($){」の「$」に注意。
◆「jQuery(document).ready(function($){」の場合:
「$()」はjQueryとして扱われる。
◆「jQuery(document).ready(function(){」の場合:
「$()」はprotoypeとして扱われ、jQueryは「jQuery()」と記述する必要がある。
私の場合、Google Maps のコードを外部ファイル化して読み込んでいるので、外部ファイルにした javascript のファイル内に、「jQuery.noConflict();」の設定を記述した。
Google Maps のコードを記述したファイル内の最初に
jQuery.noConflict();
jQuery(document).ready( function ($){
|
を記述して、最後に
を記述した。
参考サイト:
prototype.jsと同時に使うには - jQuery 日本語リファレンス
「$」を「document.getElementById」に。
jQuery では $("#ID名") のように記述して ID名要素を指定する。
prototype.jsでは「$」は、「document.getElementById」の代わりに使われる。
なので、jQuery用に「$("#ID名")」と記述している箇所は「document.getElementById("#ID名")」を使う。
【サンプルHTML】
(「address」はテキストエリアのID名とした場合。)
1 2 3 4 | <form name= "formid" id= "formid" onsubmit= "return false;" >
<input type= "text" id= "address" value= "東京タワー" >
<input type= "button" id= "btn" value= "緯度経度取得" >
</form>
|
【修正前:jQuery】
1 | var address=$( "#address" ).val();
|
【修正後:javascript】
1 | var address = document.getElementById( "address" ).value;
|
参考サイト:
小粋空間: HighSlide JS と prototype.js の競合を解消する
for-in文 ではなく for文で。
prototype.js では array に対しても拡張しており、「for-in文」を使うときちんと動作しないらしい。
そのため、「for-in文」は使わず「for文」を使う。
【修正前:for-in文】
1 2 3 | for (i in overlays){
overlays[i].setMap( null );
}
|
【修正後:for文】
1 2 3 | for ( var i=0; i < overlays.length; i++ ){
overlays[i].setMap( null );
}
|
参考サイト:
小粋空間: HighSlide JS と prototype.js の競合を解消する