我建议使用getElementById方法。添加 id 属性div
并处理onClick
事件。
<script type="javascript">
function onAClicked() {
var div = document.getElementById("hiddenDivId");
//do whatever you want to div.
}
</script>
....
<p><a href="#" class="showDivLink" onClick="onAClicked">click to show/hide div</a></p>
<div class="hiddenDiv" id="hiddenDivId">
<p>Text within hidden div.</p>
</div>
UPD:如果可以有大量与 div 的链接,我建议使用this
var。您应该执行以下操作
<script type="javascript">
function onAClicked(id) {
var div = document.getElementById("hiddenDivId" + id);
//do whatever you want to div.
}
</script>
....
<p><a href="#" class="showDivLink" id="1" onClick="onAClicked(this.id)">click to show/hide div</a></p>
<div class="hiddenDiv" id="hiddenDivId1">
<p>Text within hidden div.</p>
</div>
<p><a href="#" class="showDivLink" id="N" onClick="onAClicked(this.id)">click to show/hide div</a></p>
....
<div class="hiddenDiv" id="hiddenDivIdN">
<p>Text within hidden div.</p>
</div>
UPD2:甚至更多,您可以使用window.event
<script type="javascript">
function onAClicked() {
var e = window.event,
obj = e.target || e.srcElement,
id = e.id,
div = document.getElementById("hiddenDivId" + id);
//do whatever you want to div.
}
</script>