仅使用JavaScript选择随机HTML元素
我试图从HTML代码中选择一个元素,然后在JavaScript中使用它(需要突出显示)。HTML由一个包含36个td的表组成 到目前为止,我的代码是:仅使用JavaScript选择随机HTML元素,javascript,html,Javascript,Html,我试图从HTML代码中选择一个元素,然后在JavaScript中使用它(需要突出显示)。HTML由一个包含36个td的表组成 到目前为止,我的代码是: var box; function getRandom() { return (Math.floor(Math.random()*37)) } function highlight() { box = document.getElementById(getRandom()); box.style.backgroundCol
var box;
function getRandom()
{
return (Math.floor(Math.random()*37))
}
function highlight()
{
box = document.getElementById(getRandom());
box.style.backgroundColor = "yellow";
}
如果有人能给我指点,我将不胜感激。我知道使用jQuery很容易,但我还没有开始学习。
编辑:HTML代码的摘录,这将上升到name=“36”
您没有设置
id
属性,您正在设置name
属性,请将其更改为:
<td id="1"></td>
…etc
getElementById
获取具有匹配的id
的元素。表数据单元格根本没有id。它们有一个名称,但HTML不允许这样做
切换到id
HTML4不允许id以数字开头。使用公共字符串作为id的前缀。然后:
document.getElementById("foo" + getRandom());
有几件事:
}一种不需要设置元素ID的更好方法:
function highlight() {
// get all TDs that are descendants of table#reflexTable:
var tds = document.getElementById('reflexTable').getElementsByTagName('td');
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight td at that index
tds[rand].style.backgroundColor = "yellow";
}
这种方法的最大优点是,您可以添加/删除任意数量的TDs,而无需编辑JS以生成有效的随机数。好吧,它根本不起作用。我的输出控制台声明“box”为空。对不起,我忘了加上这个。如果你写HTML会有帮助。
没有名称
属性,谢谢。用“姓名”代替“身份证”可能是新手的错误。另外,我没有想到使用数字作为身份证是被禁止的。
function highlight() {
// get all TDs that are descendants of table#reflexTable:
var tds = document.getElementById('reflexTable').getElementsByTagName('td');
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight td at that index
tds[rand].style.backgroundColor = "yellow";
}