<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
var arr = new Array(1, 10, 8, 56, 12, 45);
document.getElementById("srt").innerHTML = arr;
function asc() {
arry.sort(function(a, b) {
return a - b;
})
document.getElementById("srt").innerHTML = arr;
}
function desc() {
arry.sort(function(a, b) {
return b - a;
})
document.getElementById("srt").innerHTML = arr;
}
</script>
</head>
<body bgcolor="aqua">
<div>
<h4>Click the button to sort the Array.</h4>
</div>
<div><input type="button" onclick="asc()" value="Ascending"></div>
<div><input type="button" onclick="desc()" value="Descending"></div>
<div>
<h4><span id="srt"></span></h4>
</div>
</body>
</html>
&#13;
请检查我的javascript代码。我想我在那里出错了。当我点击按钮时,未显示已排序的数组。
答案 0 :(得分:0)
正如Rajesh指出的那样,要么你应该在html体的末尾定义你的javascript,要么将javascript代码包装成一个结构,当你加载并准备好页面时,它将被调用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body bgcolor="aqua">
<div>
<h4>Click the button to sort the Array.</h4>
</div>
<div><input type="button" onclick="asc()" value="Ascending"></div>
<div><input type="button" onclick="desc()" value="Descending"></div>
<div>
<h4><span id="srt"></span></h4>
</div>
<script>
var arr = new Array(1, 10, 8, 56, 12, 45);
document.getElementById("srt").innerHTML = arr;
function asc() {
arr.sort(function(a, b) {
return a - b;
})
document.getElementById("srt").innerHTML = arr;
}
function desc() {
arr.sort(function(a, b) {
return b - a;
})
document.getElementById("srt").innerHTML = arr;
}
</script>
</body>
</html>
答案 1 :(得分:-1)
除了拼写错误之外,js代码中没有错误(没有为arry定义)。
问题是您在DOM准备好之前加载脚本。
在这种情况下,document.getElementById
将无效,因为DOM中不存在该元素
var arr = new Array(1, 10, 8, 56, 12, 45);
document.getElementById("srt").innerHTML = arr;
function asc() {
arr.sort(function(a, b) {
return a - b;
})
document.getElementById("srt").innerHTML = arr;
}
function desc() {
arr.sort(function(a, b) {
return b - a;
})
document.getElementById("srt").innerHTML = arr;
}
您可以在DOM准备就绪时加载代码或使用window.onload
<body>
../Rest of the code
<script>
// js code
</script>
</body>
否则,如果您仍想在标题中加载代码
`window.onload` = function() {
// your code
};
您可以探索的另一个选项是DOMContentLoaded
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// your code here
});
</script>