我正在尝试编写一个基本的“任务”功能,但遇到了一些问题。 This is what I've done so far
JS
var clicks = 0;
var coins = 10;
var Quests = function(type, required, reward, message) {
this.type = type;
this.required = required;
this.reward = reward;
this.message = message;
this.quest = function() {
if (this.type >= this.required) {
coins += this.reward;
return this.message;
} else {
alert('You don\'t have enough ' + required);
}
};
};
quest1 = new Quests(clicks, 10, 50, 'You completed this quest!');
quest2 = new Quests(clicks, 5, 50, 'You completed this quest!');
theQuests = [quest1, quest2];
$(document).ready(function() {
$('#click').click(function() {
clicks += 1;
$('#queststuff').text(clicks);
});
$('#quest').click(function() {
$('#queststuff').html(Quests[Math.floor(Math.random() * 2)].quest());
});
});
HTML
<button id="quest">quest</button>
<button id="click">click me!</button>
<div id="queststuff">
</div>
最终我将使用点击以外的其他功能,但现在我只想让基本功能正常工作。我对功能相当陌生,但目前当我单击“任务”时没有任何反应,而我希望显示警报
。我的代码中某处显然出了问题。有人能指出我正确的方向吗?
最佳答案
您正在将clicks
(一个不可变的Number
)分配给this.type
。它的值最初为 0,因此在赋值后 this.type
保持为 0。您应该在 quest
方法中将clicks
与 this.required
进行比较。
这是一个jsFiddle fork使用数据属性
关于javascript检查函数参数是否满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225622/