javascript - 选择随机元素并设置属性背景颜色
问题描述
如何为 ID 为“hello”的随机元素赋予红色?
<h1 id="hello">a</h1> <h1 id="hello">b</h1> <h1 id="hello">c</h1>
解决方案
当您使用 class 而不是 id 时,您可以执行类似的操作。
- 获取所有 hello 元素
- 在从零到元素长度的范围内创建一个随机索引
- 将 helloElements 中这个随机索引元素的 style.color 设置为红色
let helloElements = document.querySelectorAll(".hello");
let ind = (Math.floor(Math.random() * helloElements.length))
console.log(ind);
helloElements[ind].style.color = "red";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="hello">a</h1> <h1 class="hello">b</h1> <h1 class="hello">c</h1>
推荐阅读
- git - 创建合并请求后,我还可以在分支上添加提交吗?
- django - TypeError: int() 参数在迁移 django 模型期间必须是字符串
- java - 交换字符串中的字母
- html - 如何使这个 div 设备响应
- c# - 在 C# 中单击 geckoWebBrowser 中的一个链接
- python - ValueError: Error when checking input: expected conv2d_36_input to have shape (3, 32, 32) but got array with shape (1, 10, 10)
- android - 如何过滤我的 firebase 数据库并将它们添加到我的 android spinner?
- django-oscar - 价格范围方面始终禁用,计数为零
- javascript - 仅显示 while 循环中 JavaScript 的最后一个值
- c++ - 如何正确跳过 unicode (UTF-8) 字符?