gpt4 book ai didi

javascript - 如何使用javascript for循环更改文本颜色?

转载 作者:行者123 更新时间:2023-12-02 19:00:09 28 4
gpt4 key购买 nike

当有人单击文本时,它会变为红色,而单击其他文本时,它会变为黑色。我做了一个如下所示的示例,但如何使用 for 循环使其更短?

    <html>
<head>
<title>My little test page</title>
</head>
<body id="body">
<div id="myid">Hello Here !!</div><br>
<div id="myid2">Hello There !!</div><br>
<div id="myid3">Hello !!</div><br>
......many div......
</body>
</html>

<script language="javascript">
function changeColor1() {
document.getElementById("myid").className = "red";
document.getElementById("myid2").className = "";
document.getElementById("myid3").className = "";
}

function changeColor2() {
document.getElementById("myid").className = "";
document.getElementById("myid2").className = "red";
document.getElementById("myid3").className = "";
}

function changeColor3() {
document.getElementById("myid").className = "";
document.getElementById("myid2").className = "";
document.getElementById("myid3").className = "red";
}

function init() {
document.getElementById("myid").onclick = changeColor1;
document.getElementById("myid2").onclick = changeColor2;
document.getElementById("myid3").onclick = changeColor3;
}

window.onload = init();
</script>

最佳答案

为所有div添加属性名称,如下所示

<div id='myid' name='colorchangingdiv[]'>Hello</div>
<div id='myid2' name='colorchangingdiv[]'>Hello</div>
....

现在在你的初始化函数中

function init() {
var allDivs = document.getElementsByName('colorchangingdivs[]');

for( var i =0; i < allDivs.length; ++i )
{
allDivs[i].onClick = changeColor(this);
}
}

在您的更改颜色功能中

function changeColor( obj )
{
var allDivs = document.getElementsByName('colorchangingdivs[]');

for( var i =0; i < allDivs.length; ++i )
{
allDivs[i].style.color = '';
}

// Now set the color to the obj passed
obj.style.color = 'red';
}

希望有帮助。

关于javascript - 如何使用javascript for循环更改文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867544/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com