我正在尝试为对象设置新的截止日期。有时我的代码有效,有时它不会。
问题在于newStep
有时是NaN
。它应该始终是一个整数。
这是我的代码:
JS
Template.showCards.helpers({
cards: function () {
var end = moment().toDate();
// Finding the next card to show by due date
return Cards.findOne({deckId: this._id, due: {$lte: end}}, {sort: {due: -1}});
},
hard: function() {
var step = Cards.findOne({_id: this._id}).step - 1;
if (step < 0) { step = 0; }
var days = Math.pow(2.5, step);
return Math.round(days);
},
good: function() {
var step = Cards.findOne({_id: this._id}).step + 1;
if (step < 0) { step = 0; }
var days = Math.pow(2.5, step);
return Math.round(days);
},
easy: function() {
var step = Cards.findOne({_id: this._id}).step + 2;
if (step < 0) { step = 0; }
var days = Math.pow(2.5, step);
return Math.round(days);
},
});
Template.showCards.events({
// Show the answer
'click .show-answer-btn': function (event) {
$(event.target).prev().removeClass('hide');
$(event.target).next().removeClass('hide');
$(event.target).hide();
},
'click #difficulty button': function(event) {
event.preventDefault();
var step = Cards.findOne({_id: this._id}).step;
var newStep = parseInt(step) + parseInt(event.target.value);
if (newStep < 0) { newStep = 0; }
var incBy = Math.pow(2.5, newStep);
var today = moment();
if (event.target.id == 'again-btn') {
var newDue = moment(today).add(10, 'minutes').toDate();
} else {
var newDue = moment(today).add(incBy,'days').toDate();
console.log(newDue);
}
Cards.update(
this._id, {
$set: {due: newDue, step: newStep}
}
);
if (isNaN(newStep)) {
console.log("ERROR");
} else {
console.log("Success!");
}
}
});
HTML
<template name="showCards">
<div class="card">
<div class="card-content">
<p class="front">{{cards.front}}</p>
</div>
</div>
<div class="card hide">
<div class="card-content">
<p class="back">{{cards.back}}</p>
</div>
</div>
{{#with cards}}
<button class="btn btn-primary show-answer-btn">Show Answer</button>
<div id="difficulty" class="btn-group hide" role="group">
<button id="again-btn" class="btn btn-primary" value="-1">
Again
<br>
<small>10 min</small>
</button>
<button class="btn btn-primary" value="-1">
Hard
<br>
<small>{{hard}} days</small>
</button>
<button class="btn btn-primary" value="1">
Good
<br>
<small>{{good}} days</small>
</button>
<button class="btn btn-primary" value="2">
Easy
<br>
<small>{{easy}} days</small>
</button>
</div>
{{/with}}
</template>
答案 0 :(得分:1)
event.target
将引用您点击的元素。发生错误时,您已单击<small>
元素内的<button>
元素。请改用event.currentTarget
,它将引用选择器匹配的元素(在您的情况下为#difficulty button
)。