2017-04-17 5 views
2

以下は、divのクリックでコンテンツを表示および非表示にするスクリプトです。 また、最初のdivが再びクリックされるまで、他のdiv要素を無効にします。jqueryのアンバインドをトグルとして設定する方法

$('.leader-pic-wrapper').click(function(){ 
    var $el = $(this); 
    var bottom = $el.position().top + ($el.outerHeight(true) - 30); 
    $('.leader-pic-overlay').toggle(); 
    $('.leader-pic-wrapper').not(this).toggleClass('inactive-leader'); 

    /*$(".inactive-leader").unbind("click");*/ 
    $(".inactive-leader").off("click"); 

    $(this).next('.leader-profile-wrapper').css('top', bottom); 
    $(this).next('.leader-profile-wrapper').toggle(); 
}); 

アンバインドステートメントを切り替える方法がわかりません。私は非アクティブリーダーと呼ばれるクラスをトグルして、そのクラスにバインド解除を適用しようとしましたが、動作しません。

は基本的に私は

+1

? ** on()&off()** – DaniP

+0

を試してみてください。それはうまくいきました。でも、同じ要素を2回目にクリックするとどうやって解決するのですか? –

+0

バインディングの代わりにまたはバインドを解除するには、ステータスを追跡するvarを使用し、最初のバインディングを1つだけ使用し、このvar(または複数のステータスバーが複数必要な場合は配列)を更新し、ステータスをチェックします。 – Diego

答えて

2

私のオプションは、異なるビューのアプローチこれです

leader-pic-wrapper 

おかげでアンバインドを設定します。バインドとアンバインドを行わない場合は、:not()を使用して最初のセレクタで項目を除外し、除外する要素にクラスを追加します。このスニペットを確認してください。

$('body').on('click', '.box:not(".disabled")', function() { 
 
    if ($('.disabled').length) { 
 
    $(this).siblings().removeClass('disabled') 
 
    $(this).animate({ 
 
     'width': '80px' 
 
    }, 300) 
 
    } else { 
 
    $(this).siblings().addClass('disabled') 
 
    $(this).animate({ 
 
     'width': '160px' 
 
    }, 300) 
 
    } 
 
})
.box { 
 
    display: inline-block; 
 
    height: 80px; 
 
    width: 80px; 
 
    background: tomato; 
 
    margin: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div> 
 
<div class="box"></div>


あなたのコードにこのロジックは次のようになります。

使用しているバージョン
//Delegate the event since we are add/remove the class 
//Target the elements that aren't inactive 
$('body').on('click', '.leader-pic-wrapper:not(".inactive-leader")', function() { 
    var $el = $(this); 
    var bottom = $el.position().top + ($el.outerHeight(true) - 30); 

    //Check if exists some inactive elements to handle 1/2 click 
    if ($('.inactive-leader').length) { 
    //Target other leader-pic-wrapper elements, use sibling or the method you need based on your markup 
    $(this).siblings().removeClass('inactive-leader') 
    //...ACTIONS - This will act as the second click 
    } else { 
    $(this).siblings().addClass('inactive-leader') 
    //...ACTIONS - This will act as the first click 
    } 
}); 
+0

これは完全に機能しました。私がこれを完全に理解するには、少し前の文書を読む必要があります。 –

+0

このコード行についてご質問がありましたら、U @ StacyJにお越しいただき、ありがとうございます。私はそれを解決することが非常にうれしく思います。 – DaniP

+0

ねえ、私はボックス外の.box要素の中に閉じるボタンを追加する必要があります。このdivは、.boxをクリックすると開き、閉じるボタンがあります。私はコードの余分なブロックを書きました - クローズボタンをクリックするとdivを閉じ、非アクティブリーダークラスを削除します。これは正常に動作しますが、閉じるボタンを使用して閉じると、.boxは通常の方法で動作するには2回のクリックが必要です。それがどうして起こるかわかりません –

関連する問題