18910140161

JavaScript-如何在1个按钮中添加多个ID-堆栈溢出

顺晟科技

2022-10-19 14:25:25

160

我已经尝试了一个小时,以找到正确的价值这样做,现在,只有一个链接被突出显示,但我希望所有的链接得到BG的黄色,有人可以告诉我,我做了什么或我做错了什么?如何在一个按钮中添加更多的ID而不需要任何额外的代码...

<script type="text/javascript">
function hl(divId) {
    var div = document.getElementById(divId);
    div.className = "highlight";
}
function unhl(divId) {
    var div = document.getElementById(divId);
    div.className = "1";
}
</script>
<style type="text/css">
.highlight, .highlight a {
    background-color: yellow;
    font-weight: bold;
}
</style>

</head>
<body>
<div id="thinger">
   Visit  <a id="1" href="https://instagram.com/">Instagram</p></a>
   <p>Visit <a id="2" href="https://www.facebook.com/">Facebook</p></a>
        <p>Visit <a id="3" href="https://discord.gg/">Discord</p></a>
    
</div>
<button onclick="hl('1');">Highlight</button>

<button onclick="unhl('1');">Unhighlight</button>

顺晟科技:

如果要对所有锚点元素执行类似的操作,为什么不使用选择器。例如

或者如果您仍然想使用ids,请在

内部调用该函数三次
<script type="text/javascript">
function hl(divId) {
    var div = document.getElementById(divId);
    div.className = "highlight";
}
function unhl(divId) {
    var div = document.getElementById(divId);
    div.className = "1";
}
</script>
<style type="text/css">
.highlight, .highlight a {
    background-color: yellow;
    font-weight: bold;
}
</style>

</head>
<body>
<div id="thinger">
   Visit  <a id="1" href="https://instagram.com/">Instagram</p></a>
   <p>Visit <a id="2" href="https://www.facebook.com/">Facebook</p></a>
        <p>Visit <a id="3" href="https://discord.gg/">Discord</p></a>
    
</div>
<button onclick="hl('1');">Highlight</button>

<button onclick="unhl('1');">Unhighlight</button>

尝试如下代码片段:

可以使用类标记。类允许在单个按钮上使用多个类,在多个按钮上使用同一个类。

您可以使用以下代码访问带有类的每个按钮。

document.getElementsByClassName(“example”);

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航