对于我的任务,我们创建一个SVG块,用户将输入一个数字,然后我们在svg块中的随机位置向svg块添加该数量的正方形。我的代码无效。
这是我的html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.0.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Exercise 10</title>
</head>
<body>
<h1>Exercise 10</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
这是我的Javascript:
var num_squares, x, y;
num_squares = $('#howmany').val()
add_more = function() {
for (count = 0;count < num_squares;count += 1)
{
x = Math.random() * 180
y = Math.random() * 180
r = paper.rect(x, y, 20, 20)
filled = {
'fill': '#ddf'
}
r.attr(filled)
}
}
setup = function() {
paper = Raphael('svg1', 200, 200)
add_more()
}
jQuery(document).ready(setup)
这是我的CSS:
#svg1 {
border: black;
}
答案 0 :(得分:0)
您在函数外部初始化num_squares,即在文档加载时。这是在任何人输入数字之前所以num_squares总是为空,因此你的循环没有做任何事情。按下按钮时,您也无法调用add_more。
add_more = function() {
var num_squares, x, y;
num_squares = $('#howmany').val();
for (count = 0;count < num_squares;count += 1)
{
x = Math.random() * 180
y = Math.random() * 180
r = paper.rect(x, y, 20, 20)
filled = {
'fill': '#ddf'
}
r.attr(filled)
}
}
setup = function() {
paper = Raphael('svg1', 200, 200)
}
jQuery(document).ready(setup)
&#13;
#svg1 {
border: black;
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.0.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Exercise 10</title>
</head>
<body>
<h1>Exercise 10</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany">
<button id="more" onclick="add_more()">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
&#13;