gpt4 book ai didi

使用 document.addEventListener 切换链接的 Javascript 数组

转载 作者:行者123 更新时间:2023-11-28 11:03:53 26 4
gpt4 key购买 nike

Link to JS Fiddle

HTML

 <a data-info-id="show1" onclick="toggleLink();" href="#">Click here for more info</a>
<div id="show1" border="0">
More information here
</div>

CSS

    [id^="show"] { /* gets all elements where id starting with show */
display: none;
}

JS

    function toggleLink()
{
var elem=document.getElementById("show1");
var hide = window.getComputedStyle(elem, null).display =="none";
if (hide) {
elem.style.display="block";
}
else {
elem.style.display="none";
}
}

所以它的作用是在您单击链接时显示/隐藏“show1”DIV。我将使用它显示和隐藏几个 DIV 标签,它们将被命名为 id="show2"、id="show3"...等等。那么我如何使用 data-info-id 创建一个带有事件监听器的数组类似于此数组的标记,适用于复选框和单选按钮,但不适用于链接。

    document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
});

最佳答案

试试这个:

<style>
[id^="show"] { /* gets all elements where id starting with show */
display: none;
}
</style>
<script>
function toggleLink(obj)
{
var idCount = obj.id;
idCount = idCount.replace( new RegExp('c', 'g'), '');

var elem = document.getElementById("show"+idCount);

var hide = window.getComputedStyle(elem, null).display =="none";
if (hide) {
elem.style.display="block";
}
else {
elem.style.display="none";
}
}
</script>
<a id='c1' href="#" onclick="toggleLink(this)">Link1</a>
<a id='c2' href="#" onclick="toggleLink(this)">Link2</a>
<a id='c3' href="#" onclick="toggleLink(this)">Link3</a>

<div id="show1" border="0">
More information here for Div1
</div>
<div id="show2" border="0">
More information here for Div2
</div>
<div id="show3" border="0">
More information here for Div3
</div>

关于使用 document.addEventListener 切换链接的 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333279/

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