为什么onClick事件在html中只工作一次

Why does onClick event only working once in html?

本文关键字:一次 工作 事件 onClick html 为什么      更新时间:2023-09-26

我有以下html和javaScript。onclick showHiddenDev事件仅适用于第一个<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

<div id="id-2"更改为<div id="div-2"

html中有一个错误,id-2也应该是div-2。

<p class="date">Thursday Sep 11</p>
         <div id="div-2" style="display:none">Completed. 
         <a>The web page can be found at this link.</a></div>

你需要打开一个标签。