gpt4 book ai didi

javascript - 为多个相似元素触发脚本

转载 作者:行者123 更新时间:2023-11-30 13:50:14 25 4
gpt4 key购买 nike

假设我有文本:

<div class="text">Here is some text. 
In this text there are links <a href="#" class="link" id="an1">here</a>
and there are links <a href="#" class="link" id="an2">there</a>.
And there are probably many more!
They each open their own annotation on the side.</div>

我有以下要打开的注释:

<div class="annotation" id="an1">I'm the first annotation!</div>
<div class="annotation" id="an2">And I'm another one!</div>

我使用如下脚本:

function myAnnotation() {
var x = document.getElementById("an1");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}

我如何编写一个脚本来获取我的各个链接的 ID,然后打开相应的注释?

最佳答案

试试这个。

<div class="text">Here is some text. 
In this text there are links <a href="#" class="link" id="an1" data-target="an3">here</a>
and there are links <a href="#" class="link" id="an2" data-target="an4">there</a>.
And there are probably many more!
They each open their own annotation on the side.</div>

<div class="annotation" id="an3" style="display:none">I'm the first annotation!</div>
<div class="annotation" id="an4" style="display:none">And I'm another one!</div>

<script>
$('.link').on('click',function(e){

var id = e.target.attributes.getNamedItem("data-target").value;

var x = document.getElementById(id);

if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}

});

</script>

工作演示

https://jsfiddle.net/0rhnkzuj/1/

关于javascript - 为多个相似元素触发脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58406170/

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