1

onclick を使用して div のスタイルを変更したいのですが、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>

あなたが私に与えることができるどんな助けにも感謝します!!!

4

4 に答える 4

6

次のようにする必要があります。

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

イベント ハンドラーをドキュメント全体にバインドするため、e.stopPropagation().

于 2012-04-27T14:32:01.447 に答える
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");
   });
});

実際のデモ - http://jsfiddle.net/yLhsC/

ページに多くの要素がある場合は、要素のクリック イベントを処理するためにonorを使用できることに注意してください。delegateaccount

このようなもの。

onjQuery 1.7+を使用している場合の使用

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

使用するdelegate

$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
     $(".selected").removeClass("selected");
     $(this).addClass("selected");
     e.stopPropagation();//This will stop the event bubbling 
});
于 2012-04-27T14:44:29.120 に答える
0

body 要素にクリック リスナーをアタッチすることで、この動作を実現できます。

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

});
于 2012-04-27T14:31:14.480 に答える
0

これを試して:

$(document).ready(function() {

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


$(document).click(function(){  
    $('.selected').removeClass('selected');
});
});
于 2012-04-27T14:44:06.743 に答える