Newb jQuery问题:我有点迷失为什么我的jQuery函数可以工作但在我激活通过按钮链接的函数后停止工作。一切都按照我的预期运行:悬停在一行上交换添加/删除CSS并单击一个单元格打印单元格的id。但是当我点击“构建表”按钮时,jQuery部分就会停止运行。
<body>
<div id="cheese"></div>
<p id="printThis"></p>
<button id='buildTable'>Build Table</button>
</body>
<script type="text/javascript">
var myTable = "";
var pickRnd = 0;
var clickedValue;
buildTable();
function buildTable() {
$(document).ready(function() {
$("td").click(function(event) {
clickedValue = event.target.id;
document.getElementById("printThis").innerHTML = "You have selected " + clickedValue;
});
$("tr").mouseover(function() {
$(this).addClass("highlight");
});
$("tr").mouseout(function() {
$(this).removeClass("highlight");
});
$("#buildTable").click(function() {
buildTable();
});
});
myTable = "<table>";
for (var i = 0; i < 5; i++) {
pickRnd = Math.floor(Math.random() * 5);
myTable += "<tr class='normal" + pickRnd + "' id='monsterTableRow" + i + "'>";
for (var j = 0; j < 5; j++) {
myTable += "<td id='td" + j + "-" + i + "'>" + j + "-" + i + "</td>";
}
myTable += "</tr>";
}
myTable +="</table>";
document.getElementById("cheese").innerHTML = myTable;
}
</script>
答案 0 :(得分:0)
你有一些错误.... 我在这里做了一个小提琴http://jsfiddle.net/Eh5FX/1/
var myTable = "";
var pickRnd = 0;
var clickedValue;
$(document).ready(function(){
function buildTable() {
myTable = "<table>";
for (var i = 0; i < 5; i++) {
console.log(" is is " + i);
pickRnd = Math.floor(Math.random() * 5);
myTable += "<tr class='normal" + pickRnd + "' id='monsterTableRow" + i + "'>";
for (var j = 0; j < 5; j++) {
myTable += "<td id='td" + j + "-" + i + "'>" + j + "-" + i + "</td>";
}
myTable += "</tr>";
}
myTable +="</table>";
document.getElementById("cheese").innerHTML = myTable;
$("td").click(function(event) {
clickedValue = event.target.id;
document.getElementById("printThis").innerHTML = "You have selected " + clickedValue;
});
$("tr").mouseover(function() {
$(this).addClass("highlight");
});
$("tr").mouseout(function() {
$(this).removeClass("highlight");
});
}
$("#buildTable").on("click",buildTable);
});
答案 1 :(得分:0)
与上面相同,但我添加了jquery选择器,例如用$('#printThis')替换document.getElementById('printThis')。在this jsFiddle
上查看var myTable = "";
var pickRnd = 0;
var clickedValue;
function buildTable() {
$('#printThis').empty();
myTable = "<table>";
for (var i = 0; i < 5; i++) {
pickRnd = Math.floor(Math.random() * 5);
myTable += "<tr class='normal" + pickRnd + "' id='monsterTableRow" + i + "'>";
for (var j = 0; j < 5; j++) {
myTable += "<td id='td" + j + "-" + i + "'>" + j + "-" + i + "</td>";
}
myTable += "</tr>";
}
myTable += "</table>";
$("#cheese").html(myTable);
$("td").click(function (event) {
clickedValue = $(this).attr('id');
$("#printThis").html("You have selected " + clickedValue);
});
$("tr").mouseover(function () {
$(this).addClass("highlight");
});
$("tr").mouseout(function () {
$(this).removeClass("highlight");
});
}
$(document).ready(function () {
buildTable();
$("#buildTable").click(function () {
buildTable();
});
});