【发布时间】:2018-11-01 21:43:28
【问题描述】:
感谢今晚早些时候帮助我完成我的小项目的所有人。
我正在尝试重写我几周前使用 OOP javascript 编写的简单程序程序。该程序是一个反应测试器,它向用户呈现一个随机的形状,并测量用户点击该形状的速度和呈现速度。早些时候,我终于设法让一个随机大小和颜色的正方形出现在页面上。现在我正在尝试编写一个事件处理函数,该函数将在单击形状时将 css 显示属性设置为无,以便形状消失。但是,事件处理函数不起作用,到目前为止我已经尝试了几种不同的方法。请参阅下面的完整代码:
function Shape () {
this.x = Math.floor(Math.random()*1200);
this.y = Math.floor(Math.random()*500);
this.draw();
}
Shape.prototype.draw = function() {
var shapeHtml = '<div id="shape-div"></div>';
var widthAndHeight = Math.floor(Math.random()*400);
this.shapeElement = $(shapeHtml);
this.shapeElement.css({
'width': widthAndHeight,
'height': widthAndHeight,
position: "relative",
left: this.x,
top: this.y
});
this.shapeElement.css({
display: "block"
});
//Just below is where I am trying to create a function to make the shape disappear when clicked
this.shapeElement.click(function() {
this.shapeElement.css("display", "none");
});
$("body").append(this.shapeElement);
}
"use strict";
Shape.prototype.colour = function() {
var colours = '0123456789ABCDEF'.split('');
var randomColour = "#";
for (i = 0; i < 6; i++) {
randomColour+=colours[Math.floor(Math.random()*16)];
};
this.shapeElement.css({backgroundColor: randomColour});
}
$(document).ready(function() {
var square = new Shape();
square.draw();
square.colour();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这行不通。我正在向 OOP 过渡,并发现使用过程编程来做一些小菜一碟真的很困难。这是典型的吗?再次感谢您的帮助。
【问题讨论】:
标签: javascript jquery oop