2012-04-27 14 views
1

divのスタイルをonclickで変更したいと思います。divの外側をクリックするとスタイルが削除されます。Onclickの変更divのスタイル+ onclickのdivの外側のスタイルの変更の変更

私は次のコードの設定をしています...ページの他の場所をクリックすると誰かがdivのスタイルを削除できますか?

<head> 
    <style type="text/css"> 
    .account{ 
     width: 100px; 
     height: 100px; 
     border: 1px solid #000; 
    } 
    .selected{ 
    border: 2px solid #F00; 
    } 
    </style> 
    <script type="text/javascript"> 
    $(document).ready(function(){ 
    $(".account").click(function(){ 
    $(".selected").removeClass("selected"); 
    $(this).addClass("selected"); 
    }); 
    }); 
    </script> 
</head> 
<body> 
<h1>the test</h1> 
<div class="account">test 1</div> 
<div class="account">test 2</div> 
</body> 

ありがとうございました。私に教えていただきありがとうございます!

答えて

2

はこれを試してみてください。

$(document).ready(function(){ 
    $(".account").click(function(e){ 
     $(".selected").removeClass("selected"); 
     $(this).addClass("selected"); 
     e.stopPropagation();//This will stop the event bubbling 
    }); 

    //This event handler will take care of removing the class if you click anywhere else 
    $(document).click(function(){ 
     $(".selected").removeClass("selected"); 
    }); 
}); 

の作業のデモ - あなたがページ上の多くがある場合account要素にイベントをクリックし処理するためにonまたはdelegateを使用することができますhttp://jsfiddle.net/yLhsC/

注意。

このようなものです。あなたが実際のターゲットをクリックすると、まだ起動されますdelegate

$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){ 
    $(".selected").removeClass("selected"); 
    $(this).addClass("selected"); 
    e.stopPropagation();//This will stop the event bubbling 
}); 
+0

ありがとうございました!これは完璧に機能しました! – lbriquet

+0

Kool、答えとしてマークしてください。 – ShankarSangoli

0

あなたは例えばbody要素のクリックリスナーを取り付けると、この動作を実現することができます。

$("body").click(function(){ 

}); 
+0

このハンドラを使用してjQueryの1.7以降

$('parentElementContainingAllAccounts').on('click', '.account', function(e){ $(".selected").removeClass("selected"); $(this).addClass("selected"); e.stopPropagation();//This will stop the event bubbling }); 

使用している場合onを使用して

。 – Joseph

+0

はい、それは本当です...申し訳ありませんが、divハンドラのreturn falseを追加する必要があることに言及するのを忘れてしまいました。 – bacardnumberone

6

次はそれを行う必要があります。

$(document).on('click', function(e) { 
    if($(e.target).hasClass('account')) { 
     // do style change 
    } 
    else { 
     // undo style change 
    } 
}); 

それは文書全体にイベントハンドラをバインドするので、あなたe.stopPropagation()という特定の要素のイベントハンドラに問題があります。

0

はこれを試してみてください:

$(document).ready(function() { 

$('.account').click(function(e) { 
    e.stopPropagation(); 
    $(this).addClass("selected"); 
}); 


$(document).click(function(){ 
    $('.selected').removeClass('selected'); 
}); 
}); 
関連する問題