javascript - 我正在尝试将我的函数调用存储在一个对象中
问题描述
我试图将我的函数调用存储在一个对象中,所以当我引用该属性时,它会运行该函数。这是我写的代码,但它不起作用。到目前为止,这是我的代码。html:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris(test)</title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
<script src = "js/jquery.1.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<svg id="container" width= "500" height= "650" style= "background-color: black" position= "relative">
</svg>
</body>
</html>
JS:
var svgNS = "http://www.w3.org/2000/svg";
var htmlNS = "http://www.w3.org/1999/xhtml";
function createShape1() {
var elem = document.getElementById("container");
var shape = document.createElementNS(svgNS, "rect");
shape.id = "shape1";
shape.style.width = "150px";
shape.style.height = "50px";
shape.style.fill = "orange";
shape.style.y = "50px";
shape.style.x = "150px"
shape.style.position = "absolute"
elem.append(shape);
var shape2 = document.createElementNS(svgNS, "rect");
shape2.id = "shape2";
shape2.style.fill = "orange";
shape2.style.x = "200px";
shape2.style.width = "50px";
shape2.style.height = "51px";
elem.append(shape2);
};
window.onload = randShape;
function createShape2() {
var elem = document.getElementById("container");
var shape = document.createElementNS(svgNS, "rect");
shape.id = "shape1";
shape.style.width = "100px";
shape.style.height = "100px";
shape.style.fill = "red";
shape.style.x = "200px"
shape.style.position = "absolute"
elem.append(shape);
};
var shapes = {
"shape1": createShape1(),
"shape2": createShape2()
};
function randShape() {
var x = Math.floor(Math.random() * 2);
shapes.x;
}
因此,如果您有任何建议让我的代码生成形状的随机属性,每个属性都应该生成自己的形状。
解决方案
问题是如何在访问要调用的函数之前访问该值并进行函数调用
var shapes = {
"shape1": createShape1,
"shape2": createShape2
};
function randShape() {
var x = Math.floor(Math.random() * 2) + 1;
(shapes["shape" + x]).call(shapes);
}
推荐阅读
- vba - 刷新后从页面下载数据
- php - 如何在 Symfony/PHP 中处理错误的 CSV 文件导入
- express - 不推荐使用正文解析器
- azure - Azure 事件中心在一个应用程序中提供多个消费者
- snowflake-cloud-data-platform - 我在 redshift 中有一个存储过程,我必须将其转换为雪花过程。雪花中的IN、OUT和INOUT参数如何处理?
- sql - SQL 显示计数结果,即使它是 0
- amazon-web-services - 如何检查代理是否干扰了 AWS CLI 命令以检索 S3 详细信息?
- json - 在 post 方法中,请求正文中 json 的限制大小是多少?
- hangfire - Hangfire 仪表板授权重定向以登录
- javascript - process.env.EDGE_APP_ROOT 是什么?