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

时间:2014-09-24 14:39:02

标签: javascript jquery html5

我有以下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中多次工作?

3 个答案:

答案 0 :(得分:1)

   <div id="div-1" style="display:none">Completed</div>
            ^^^^---- spot the difference
     <div id="id-2" style="display:none">Completed. 
              ^^^^--- spot the difference

答案 1 :(得分:1)

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

答案 2 :(得分:1)

你的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>

您需要打开标签。