Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅使用JavaScript选择随机HTML元素_Javascript_Html - Fatal编程技术网

仅使用JavaScript选择随机HTML元素

仅使用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

我试图从HTML代码中选择一个元素,然后在JavaScript中使用它(需要突出显示)。HTML由一个包含36个td的表组成

到目前为止,我的代码是:

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());
有几件事:

  • 您应该在highlight函数中声明box变量

  • 您必须将该随机数转换为字符串

  • 昆廷提到了一件重要的事情——您应该给每个表元素一个id,比如“s0”、“s1”、“s2”等等

  • 从0开始命名,因为getRandom函数有时会返回它

  • 函数高亮显示(){ var数; number=getRandom().toString(); var盒; box=document.getElementById(“s”+编号); box.style.backgroundColor=“黄色”;
    }一种不需要设置元素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";
    
    }