我有以下 html 和 javaScript。 onclick showHiddenDiv 事件仅适用于第一个 <li>
.
<!DOCTYPE html>
<html>
<body>
<ul class="list">
<li>
<h3 class="assignments"><a href="#users" onclick="showHiddenDiv('div-1')">
Assignment 1</a></h3>
<p class="date">Tuesday Sep 9</p>
<div id="div-1" style="display:none">Completed</div>
</li>
<li>
<h3 class="assignments"><a href="#users" onclick="showHiddenDiv('div-2')">
Assignment 2 </a></h3>
<p class="date">Thursday Sep 11</p>
<div id="id-2" style="display:none">Completed.
The web page can be found at this link.</a></div>
</li>
</ul>
<script>
function showHiddenDiv(id) {
"use strict";
var obj = document.getElementById(id);
if (obj.style.display === "none") {
obj.style.display = 'block';
} else if (obj.style.display === "block") {
obj.style.display = 'none';
}
}
</script>
</body>
</html>
如何使用 onclick 调用 javaScript 函数以在 html 中多次工作?
最佳答案
<div id="div-1" style="display:none">Completed</div>
^^^^---- spot the difference
<div id="id-2" style="display:none">Completed.
^^^^--- spot the difference
关于javascript - 为什么 onClick 事件在 html 中只工作一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019724/