jQueryが動かない場合にまず試してみるべき有効な対処法

jQueryが動いていないように思える場合に、まず試してみるべき方法があります。

jQueryのコードをfunctionで囲む

[javascript]
(function($){
コード
}(jQuery))
[/javascript]

という形式でコードを囲むと、jQueryがあっさりと動くことがあります。

例えば、チェックボックスの背景色を制御する下記のjQueryのコードが動かない場合、
[javascript]
$(function(){
$(“table td:has(input[type=checkbox])”).hover(function(){
$(this).css(“background-color”,”#efefef”);
},function(){
$(this).css(“background-color”,”transparent”);
});

$(“table td:has(input[type=checkbox])”).click(function(){
var chkb = $(this).children(“input[type=checkbox]”);
if(chkb.attr(“checked”)) {
chkb.attr(‘checked’, false);
}else{
chkb.attr(‘checked’, true);
}
});
$(“table td input[type=checkbox]”).click(function(){
if($(this).attr(“checked”)) {
$(this).attr(‘checked’, false);
}else{
$(this).attr(‘checked’, true);
}
});
});
[/javascript]

そのjQueryを囲むと、下記のようになります。

[javascript]
(function($){//これで囲む

$(function(){
$(“table td:has(input[type=checkbox])”).hover(function(){
$(this).css(“background-color”,”#efefef”);
},function(){
$(this).css(“background-color”,”transparent”);
});

$(“table td:has(input[type=checkbox])”).click(function(){
var chkb = $(this).children(“input[type=checkbox]”);
if(chkb.attr(“checked”)) {
chkb.attr(‘checked’, false);
}else{
chkb.attr(‘checked’, true);
}
});
$(“table td input[type=checkbox]”).click(function(){
if($(this).attr(“checked”)) {
$(this).attr(‘checked’, false);
}else{
$(this).attr(‘checked’, true);
}
});
});

}(jQuery));//これで囲む
[/javascript]

これで、jQueryが動くようになる場合がありますので、まずは試してみる価値があるかもしれません。

jQueryデザインブック 仕事で絶対に使うプロのテクニック
jQueryデザインブック 仕事で絶対に使うプロのテクニック

コメント

  1. […] ・javascript周り jQueryが動かない場合にまず試してみるべき有効な対処法(これは本気で助かった) […]