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

标签 javascript jquery html css

假设我有文本:

<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/

相关文章:

javascript - querySelectorAll 返回什么类型的数据?

javascript - 删除所有包含空白 href 的链接并将其替换为仅在 Javascript 中的文本?

javascript - 如何从 Firebase Cloud 功能中删除用户数据(任何数据)?

javascript - 如何判断浏览器/选项卡是否处于事件状态,并在用户离开时调低音量

html - z-index 不适用于重叠元素

javascript - 如何从外部 javascript 文件调用 tiny_mce.init

php - 合并日期和时间后显示 PHP fatal error

javascript - angularjs $location.path.replace 不工作

javascript - 合并 JavaScript 和 CSS 文件时如何更新 HTML 脚本和链接引用?

html - 如何在 Node.js 服务器中隐藏 .html 扩展名?