gpt4 book ai didi

javascript - 通过ID更改标签背景颜色

转载 作者:行者123 更新时间:2023-11-28 09:09:54 25 4
gpt4 key购买 nike

HTML 是这样的:

     <div class="header">
<ul>
<li>
<a class="abc" id="abc" href="www.testing.com">testing</a>
</li>
</ul>
</div>

我的 JavaScript 是这样的:

    <script language="javascript" type="text/javascript">
var links = document.getElementById("abc");
var a = links.getElementsByTagName("a");
var thisLocationHref = window.location.href;
for(var i=0;i<a.length;i++)
{

var tempLink = a[i];

if(thisLocationHref === tempLink.href)
{
tempLink.style.backgroundColor="red";
}
else
{
tempLink.style.backgroundColor="blue";
}
}

我无法删除 a 标记中的 ID,因为它与另一个页面相关。我知道代码中有问题,但无法找出问题所在。欢迎任何帮助!谢谢!

最佳答案

id="abc" 赋予 ul 并将其从 a 标记中删除,您的代码即可运行。

演示: http://jsfiddle.net/BgbjD/

来自 MDN:

element.getElementsByTagName

Returns a list of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself.

所以你必须搜索ul节点。

<div class="header">
<ul id="abc">
<li> <a class="abc">testing</a>
</li>
</ul>
</div>

您的 JavaScript 不需要任何更改。

关于javascript - 通过ID更改标签背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452229/

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