我最终试图设置它,以便在单击标题时,它将对表进行排序。现在我只是想让它提醒(" Hello world")以确保我正确设置它。目前" myFunction"加载页面时发生。我希望按下按钮时发生这种情况。谢谢你的帮助。这是代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=Windows-1252">
</head>
<body>
<div id="catTable"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
function renderData(cats){
var output='<table id="indextable" border="1" cellpadding="10" cellspacing="0" style="border-collapse:collapse;">';
output+="<thead>"
output+="<tr>";
output+="<th> HeadShot </th>";
output+="<th> Breed </th>";
output+="<th><button onclick='" + myFunction() + "'>Country</button></th>"; // myFunction happens when page is loaded
output+="<th> CoffeePreference </th>";
output+="</tr>";
output+="</thead>"
for (var i in cats) {
output+="<tbody>"
output+="<tr>";
output+="<td><img src='" + cats[i].picture+"' alt='missing cat picture'></td>"
output+="<td>" + cats[i].breed + "</td>"
output+="<td>" + cats[i].country + "</td>"
output+="<td>" + cats[i].coffeePreference + "</td>"
output+="</tr>";
output+="</tbody>"
}
output+="</table>";
document.getElementById("catTable").innerHTML=output;
}
function getData(){
$.getJSON('cats.json', function(cats) {
var cats = cats;
sortData(cats, 'coffeePreference');
});
}
function sortData(cats, element){
switch(element) {
case 'breed':
var sortedData = cats.sort(function(a,b){return (a.breed < b.breed) ? -1 : 1;});
renderData(cats);
break;
case 'country':
var sortedData = cats.sort(function(a,b){return (a.country < b.country) ? -1 : 1;});
renderData(cats);
break;
case 'coffeePreference':
var sortedData = cats.sort(function(a,b){return (a.coffeePreference < b.coffeePreference) ? -1 : 1;});
renderData(cats);
default:
renderData(cats);
}
}
function myFunction() {
alert("Hello World");
}
getData();
</script>
</body>
</html>
答案 0 :(得分:4)
这是因为这一行
<button onclick='" + myFunction() + "'>Country</button></th>
这将立即调用该函数。这里不需要字符串连接,只需将其写入:
<button onclick='myFunction()'>Country</button></th>
答案 1 :(得分:0)
你几乎得到了它。问题出在这一行:
output+="<th><button onclick='" + myFunction() + "'>Country</button></th>";
应该是:
output+="<th><button onclick='myFunction()'>Country</button></th>";