我正在制作一款游戏,其中的谚语会显示在表格中。当您单击其中一个字母(或 td)时,它会显示该字母。
在删除空格/作者/等之后,我使用 Javascript 创建了表格。这是我用来创建表格的代码。
function createRow(tableRowId, startIndex, endIndex) {
var row = document.getElementById(tableRowId);
var index = startIndex;
while(index <= endIndex){
//hints array contains the letters to be displayed
if(hints[index] != undefined){
var newCell = row.insertCell(-1);
var newText = document.createTextNode(hints[index]);
newCell.appendChild(newText);
}
else{
break;
}
index++;
}
我遇到的问题是 onclick 无法与刚创建的 td 一起使用。
var cells = document.getElementsByTagName("td");
cells.onclick = function (){
cells.style.backgroundColor = "white";
}
我一定是漏掉了某个步骤或其他什么,也许是我的代码中出现了一些小错误。也许有更好的方法来做到这一点。所有的来源都可以在这里找到。 http://wikisend.com/download/831324/lab4.zip
最佳答案
我将更新一种方法,将突出显示切换到仅一个单元格。
编辑
好的,这里有一个方法可以删除 blue
类并将其添加到被单击的类中:
// Remember el.attachEvent('onclick', ...) for IE8 and lower
base.addEventListener('click', function delegate(e){
var cells = tbody.getElementsByClassName('blue'),
i = 0,
cell;
while (cell = cells[i++]) {
cell.className = cell.className.replace(/\bblue\b/g, '');
}
e.target.className += ' blue';
});
这使用 el.getElementsByClassName()
,大多数现代浏览器和 IE9 及更高版本都支持它。当然,另一种方法是执行另一个普遍支持的 tbody.getElementsByTagName('td')
。
编辑 2
请注意,我注意到有时可以不点击 TD
,因此我们应该首先检查这一点,如果不是 ,则忽略对
:table
的点击TD
base.addEventListener('click', function delegate(e){
var cells = tbody.getElementsByClassName('blue'),
i = 0,
cell;
if (e.target.nodeName.toLowerCase() == 'td') {
while (cell = cells[i++]) {
cell.className = cell.className.replace(/\bblue\b/g, '');
}
e.target.className += ' blue';
}
});
HTML
<table id="base">
<tbody></tbody>
</table>
Javascript
var base = document.getElementById('base'),
tbody = base.getElementsByTagName('tbody')[0],
numrows = 30,
numcols = 10,
col = 0,
row = "<tr>{row}</tr>",
rows = "",
cell = "<td>{cell}</td>",
cells = "";
// Remember el.attachEvent('onclick', ...) for IE8 and lower
base.addEventListener('click', function delegate(e){
e.target.style.backgroundColor = 'blue';
});
while (numrows--) {
cells = "";
col = 0;
while (col++ < numcols) {
cells += cell.replace('{cell}', col);
}
rows += row.replace('{row}', cells);
}
tbody.innerHTML = rows;
关于JavaScript 表 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537803/