【发布时间】:2010-05-09 02:39:47
【问题描述】:
我正在尝试使用 .push 将项目放入 javascript 数组中。我创建了一段简化的代码。当我单击 ID 为 clickButton 的按钮时,我希望收到一系列带有数字的警报,但我什么也没得到。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sempedia | Making computers think about data the way we do</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready( function() {
var myArray = new Array(); //declare the array
for(var i=0;i<=10;i++){ // create a loop
myArray.push(i); // add an item to array
}
$("#clickButton").live('click',function() { //register the button being clicked
for(var j=0;j<=10;j++){ //for loop
alert(myArray[j]); //alert one item in the array
}
});
});
</script>
</head>
<body>
<input type="button" value="click me" id="clickButton" />
</body>
</html>
【问题讨论】:
-
代码看起来不错,请确保 jQuery 确实被包含...
-
当您遇到编程问题时,您应该始终做的第一步是检查错误消息。
-
您可以使用
[]代替new Array()创建一个空数组。
标签: javascript arrays