点击骰子赢得't工作(javascript)

Clicking on Dice won't work (javascript)

本文关键字:工作 javascript      更新时间:2024-02-04

我正在尝试初始化一个骰子,并根据点击进行滚动。这就是我到目前为止所想到的。当我在控制台中点名时,它可以工作,但当我点击时,它不会工作。

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();
});

您所拥有的许多问题:

  • 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();
d6 {
    font-size: 600%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>