jQueryで変数を追加する際に役立つアドバイスツールを作成しています。jQuery未定義変数を無視する
複数の選択肢の回答には特定のデータ属性があり、特定の変数に保存する必要があります。後でユーザーが同じデータ属性をクリックした場合、値は以前の値(varに格納されている値)まで加算する必要があります。
問題点:すべての回答にデータ属性があるわけではありません。ユーザーがデータ属性なしで回答をクリックするたびに、変数は「未定義」に変わり、使用不能になります。
私はこの問題を示すためにjsfiddleに私のコードのショートバージョンを変換:
// The default is 0
var count_health = 0;
var count_fat = 0;
$('.question div').click(function(){
// I want to get the data from the answer
var gather_health = $(this).attr("data-health");
var gather_fat = $(this).attr("data-fat");
// And add it up to the variable
count_health = +count_health + +gather_health;
count_fat = +count_fat + +gather_fat;
// And show it
$('.health').text('Your health is: ' + count_health);
$('.fat').text('Your fat is: ' + count_fat);
});
.question div {
background-color: #f4f4f4;
padding: 5px;
cursor: pointer;
width: 50px;
margin-top: 5px;
}
.health {
display: block;
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Shows health -->
<span class="health"></span>
<span class="fat"></span>
<!-- Questions & Answers -->
<div class="question">
<h2>Do you run?</h2>
<div data-health="1">Yes</div>
<div>No</div>
</div>
<div class="question">
<h2>Do you eat fruit?</h2>
<div data-health="1">Yes</div>
<div>No</div>
</div>
<div class="question">
<h2>Do you eat chips?</h2>
<div data-fat="1">Yes</div>
<div>No</div>
</div>
変数を計算するためのより効率的な方法があるかどうかはわかりません。あなたが1つを知っていれば、私はそれを見てうれしいです!しかし、私はあなたのようなjQueryウィザーズではありません:-)
よく、属性がない場合はどうしますか? –
@EvanMosseri何もしないか、 "0"として扱います。現在のデータを使用するだけです。 –