所以说我有文字:
<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,然后打开适当的注释?
答案 0 :(得分:1)
function myAnnotation(argument) {
var x = document.getElementById("an" + argument);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
<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" onclick="myAnnotation(1)">I'm the first annotation!</div>
<div class="annotation" onclick="myAnnotation(2)">And I'm another one!</div>
注意:-您需要创建一个函数并将该函数绑定到onClick并在此处传递参数。这样您就可以动态隐藏该功能。
希望这会有所帮助!
答案 1 :(得分:1)
尝试这个。
<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>
工作演示
答案 2 :(得分:0)
首先:您不能两次(或多次)使用相同的ID
如果了解您的问题,则希望显示有关用户操作的元素(例如单击)
我建议不要切换显示。
function myAnnotation(id) {
var x = document.getElementById(id);
x.style.display = "block";
}
<div class="text">Here is some text.
In this text there are links
<a href="#" class="link" onClick="myAnnotation('an1')">here</a>
and there are links
<a href="#" class="link" onClick="myAnnotation('an2')">there</a>.
And there are probably many more!
They each open their own annotation on the side.</div>
<div class="annotation" style="display:none" id="an1">I'm the first annotation!</div>
<div class="annotation" style="display:none" id="an2">And I'm another one!</div>