2017-08-13 8 views
2

整数の要素を持っています。単一要素のクリックで増減カウントを切り替えます。

<span class="likes-count"> 2 </span>

そして、クリックされたdivの値の増減を切り替える必要があります。 <div class="liked"></div>

問題: 私は値をインクリメントし.notliked にクラスを変更し、別のonclick関数は値をデクリメント$('.liked').clicked上の関数を呼び出していますが、それが正常に動作していません。 私のコードを確認してください。私はこれがこれを行う最善の方法ではないと思います。

私のデモコードです。あなたは、クリックイベントを委任する必要が

$(document).ready(function() { 
 
    $(".notliked").click(function() { 
 
     var $this = $(this); 
 
     $this.removeClass('notliked'); 
 
     $this.addClass('liked') 
 
     $count = $('.likes-count'); 
 
     $count.html((parseInt($count.html(),10) || 0) + 1); 
 

 
    }); 
 

 
    $(".liked").click(function() { 
 
     var $this = $(this); 
 
     $this.removeClass('liked'); 
 
     $this.addClass('notliked'); 
 
     $count = $('.likes-count'); 
 
     $count.html((parseInt($count.html(),10) || 0) - 1); 
 

 
    });   
 
});
.heart { 
 
    color: #fff; 
 
    height:50px; 
 
    cursor:pointer; 
 
    width:50px; 
 
    background-color: red; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
 

 
<span class="likes-count"> 2 </span> 
 

 
<div class="liked heart">Click</div>

+0

を使用する場合があります代わりに '.toggleClass()'を使います。 - http:// api。 jquery.com/toggleclass/ –

+0

私はそれを試みました。私の問題ではうまくいかなかった。 – Saurabh

答えて

2

。最初は$( "。notliked")は0個の要素を返し、実行されることはありません。

.text(function)のような:あなたが使用できるテキスト値デクリメント/インクリメントするために

$count.text(function(idx, txt) { 
    // convert text to number and increment by one 
    return +txt + 1; 
}); 

をスニペット:

$(document).on('click', ".notliked", function() { 
 
    var $this = $(this); 
 
    $this.removeClass('notliked'); 
 
    $this.addClass('liked') 
 
    $count = $('.likes-count'); 
 
    $count.text(function(idx, txt) { 
 
     return +txt + 1; 
 
    }); 
 

 
}); 
 

 
$(document).on('click', ".liked", function() { 
 
    var $this = $(this); 
 
    $this.removeClass('liked'); 
 
    $this.addClass('notliked'); 
 
    $count = $('.likes-count'); 
 
    $count.text(function(idx, txt) { 
 
     return (+txt == 0) ? 0 : (+txt - 1); 
 
    }); 
 

 
});
.heart { 
 
color: #fff; 
 
height:50px; 
 
cursor:pointer; 
 
width:50px; 
 
background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<span class="likes-count"> 0 </span> 
 

 
<div class="liked heart">Click</div>

+0

それは働いている。もう1つの質問。初期カウントが0の場合、-1に減らしたくありません。あなたはそれを達成する方法を教えてください:) – Saurabh

+0

@Saurabh回答とスニペットが更新されました。 – gaetanoM

関連する問題