我有一个按钮,上面写着我点击它时没有响应的Top Add。它被禁止做的是警告它刚刚添加的变量,但它什么也没做。这是我的代码:
$("button#left").click(function(){
moveLeftId[moveLeftId.length]="-=50px";
alert(moveLeftId);
});
$("button#start").click(function(){
alert("You clicked action!");
var i;
for (i = 0; i < moveLeftId.length; i++) {
$("div#test").animate({
marginLeft: moveLeftId[i]
}, 500);
}
for (i = 0; i < moveTopId.length; i++) {
$("div#test").animate({
marginTop: moveTopId[i]
}, 500);
}
});
/*
$("button#top").click(function(){
moveTopId[moveTopId.length]="+=50px";
});marginTop: moveTopId[i]*/
&#13;
#test {
width: 100px;
height: 100px;
background-color: #C00;
margin-left: 500px;
margin-top:300px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" color="white">Hi</div>
<button id="left">Left add</button>
<button id="start">Action!</button>
<button id="top" onclick="moveTopId[moveTopId.length]='-=50px';
alert(moveTopId);">Top add</button>
<script>var moveLeftId=new Array(["-=50px"]);
var moveBottomId=new Array(["-=50px"]);</script>
&#13;
如您所见,我尝试将一些代码分离到其他脚本标记中,但这并没有什么不同。我不知道该怎么做!
提前致谢!
答案 0 :(得分:2)
$("button#left").click(function(){
moveLeftId[moveLeftId.length]="-=50px";
alert(moveLeftId);
});
$("button#start").click(function(){
alert("You clicked action!");
var i;
for (i = 0; i < moveLeftId.length; i++) {
$("div#test").animate({
marginLeft: moveLeftId[i]
}, 500);
}
for (i = 0; i < moveTopId.length; i++) {
$("div#test").animate({
marginTop: moveTopId[i]
}, 500);
}
});
/*
$("button#top").click(function(){
moveTopId[moveTopId.length]="+=50px";
});marginTop: moveTopId[i]*/
&#13;
#test {
width: 100px;
height: 100px;
background-color: #C00;
margin-left: 500px;
margin-top:300px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" color="white">Hi</div>
<button id="left">Left add</button>
<button id="start">Action!</button>
<button id="top" onclick="moveTopId[moveTopId.length]='-=50px';
alert(moveTopId);">Top add</button>
<script>var moveLeftId=new Array(["-=50px"]);
var moveBottomId=new Array(["-=50px"]);var moveTopId =new Array(["-=50px"]);
</script>
&#13;
答案 1 :(得分:1)
您没有定义此数组,因此如果未定义,则无法获取Array.length。
您的脚本正常工作只需要在开始时定义此变量。
var moveLeftId = [];
var moveTopId = [];
$("button#left").click(function(){
moveLeftId[moveLeftId.length]="-=50px";
alert(moveLeftId);
});
$("button#start").click(function(){
alert("You clicked action!");
var i;
for (i = 0; i < moveLeftId.length; i++) {
$("div#test").animate({
marginLeft: moveLeftId[i]
}, 500);
}
for (i = 0; i < moveTopId.length; i++) {
$("div#test").animate({
marginTop: moveTopId[i]
}, 500);
}
});
$("button#top").click(function(){
moveTopId[moveTopId.length]="+=50px";
});
答案 2 :(得分:0)
尝试在
中添加代码$( document ).ready(function() {
// put code here
});
这是因为如果在页面加载完成之前运行了JS和JQuery ..