我正在尝试初始化骰子并根据点击滚动它。这是我到目前为止所提出的。当我在控制台中调用roll时它会起作用,但是当我点击它时它不会工作。
function Dice() {
this.die = randInt(0,5);
this.icons = "⚀⚁⚂⚃⚄⚅";
this.el = "<d6>" + this.icons.charAt(this.die) + "</d6>";
}
Dice.prototype.render = function() {
$( "d6" ).remove();
$("body").append(this.el);
}
Dice.prototype.roll = function() {
this.die = randInt(0,5);
this.el = "<d6>" + this.icons.charAt(this.die) + "</d6>";
this.render();
}
这是我一直在尝试的点击功能。有什么帮助吗?
var dice = this;
$("this.el").click(function(){
dice.roll();
});
答案 0 :(得分:0)
你在那里遇到的一些问题:
Dice()
构造函数后出现语法错误(迷路);
)。$("this.el")
毫无意义,即使您使用$(this.el).click()
,$(this.el)
实际上也会创建一个新元素(因为this.el
是一个HTML字符串),而不是选择您添加到页面的那个。对第一颗子弹的补救是不言而喻的。为了解决问题,我已经修改了您分配到this.el
的地方,以便在那里创建元素。
以下内容应该有效:
function randInt(min, max) {
return ~~(Math.random() * (max - min + 1) + min);
}
function Dice() {
this.die = randInt(0,5);
this.icons = "⚀⚁⚂⚃⚄⚅";
}
Dice.prototype.render = function() {
$( "d6" ).remove();
$("body").append(this.el);
var dice = this;
console.log(this.el);
this.el.click(function(){
dice.roll();
});
}
Dice.prototype.roll = function() {
this.die = randInt(0,5);
this.el = $("<d6>" + this.icons.charAt(this.die) + "</d6>");
this.render();
}
var d = new Dice();
d.roll();
&#13;
d6 {
font-size: 600%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
&#13;