这是我的代码,我的代码在随机位置gerenate方框但每次点击时都会进行克隆。我想在每次点击按钮时都指向正方形。当我点击时,我正在克隆。如何解决这个问题。
<!DOCTYPE html>
<html>
<head>
<title>SYST24444</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript" src="./js/libs/jquery/jquery.min.js"></script>
<style>
body, html {
width: 960;
height: 100%;
}
div.box {
position: relative;
width: 100px;
height: 100px;
background-color: orange;
}
div.exploding {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="button">Blue</button>
<script>
$(document).ready(function () {
makeDiv();
function makeDiv() { //random position
var numRand = Math.floor(Math.random() * 501);
var divsize = 100;
var posx = (Math.random() * ($('body').width() - divsize)).toFixed();
var posy = (Math.random() * ($('body').height() - divsize)).toFixed();
$newdiv = $("<div class='exploding'></div>").css({
'left': posx + 'px',
'top': posy + 'px'
});
$("#button").click(function(){ //click function
$newdiv.appendTo('body').ready(function(){
makeDiv();
});
});
};
});
</script>
</body>
</html>
答案 0 :(得分:0)
您可以将click
处理程序移到makeDiv
函数之外,从$newdiv
调用返回makeDiv()
,然后将.appendTo("body" /* or other selector */)
链接到makeDiv()
$(document).ready(function() {
makeDiv().appendTo("body");
function makeDiv() { //random position
var numRand = Math.floor(Math.random() * 501);
var divsize = 100;
var posx = (Math.random() * ($('body').width() - divsize)).toFixed();
var posy = (Math.random() * ($('body').height() - divsize)).toFixed();
$newdiv = $("<div class='exploding'></div>").css({
"left": posx + "px",
"top": posy + "px"
});
return $newdiv
};
$("#button").click(function() { //click function
makeDiv().appendTo("body");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>SYST24444</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style>
body,
html {
width: 960;
height: 100%;
}
div.box {
position: relative;
width: 100px;
height: 100px;
background-color: orange;
}
div.exploding {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button id="button">Blue</button>
<script>
$(document).ready(function() {
makeDiv().appendTo("body");
function makeDiv() { //random position
var numRand = Math.floor(Math.random() * 501);
var divsize = 100;
var posx = (Math.random() * ($('body').width() - divsize)).toFixed();
var posy = (Math.random() * ($('body').height() - divsize)).toFixed();
$newdiv = $("<div class='exploding'></div>").css({
'left': posx + 'px',
'top': posy + 'px'
});
return $newdiv
};
$("#button").click(function() { //click function
makeDiv().appendTo("body");
})
});
</script>
</body>
</html>