JavaScript 函数将打开 div 标签;第二个 JavaScript 函数不会关闭它

JavaScript function will open div tag; second JavaScript function does not close it however

我一直在浏览这里并查看类似的问题,但是 none 的解决方案似乎有效。这也是我第一个发布的问题。

<table>
<tr class="foo" onclick="openEmail1();">...</tr>
<tr class="foo" onclick="openEmail2();">...</tr>
<tr class="foo" onclick="openEmail3();"> <!-- this opens fine-->
  <td>From: Me</td>
  <td>Subject: Why won't this work?</td>
  <td>Date:

  <div style="display: none" id="email3">..email popup..

    <div>...header box in email popup...</div>
    <div>...email body box in email popup...</div>
    <div>
      <button onclick="openForm();">Forward</button> <!-- this works fine-->
      <button onclick="closeEmail3();">Close</button> <!-- does not work-->
    </div>

  </div>
  <script>
  function openEmail3(){
    document.getElementById("email3").style.display = "block";
  }
  function closeEmail3(){
    document.getElementById("email3").style.display = "none";
  }
  </script>
  </td>
</tr>
</table>
这只是一个伪代码,但我 运行 这个和它的工作原理(或不工作)与我的完全一样。我不明白为什么 closeEmail 功能不起作用。

使用这个

<button type="button" onclick="closeEmail3();">Close</button>

<input type="button" onclick="closeEmail3();" value="Close" />

由于 event bubbling

,您的代码无法正常工作

我更新了你的代码,将你的元素放在 var 中,使其更易读

 var div = document.getElementById("email3");

将按钮元素更改为此将停止默认功能

<button onclick="closeEmail3();event.stopPropagation()">Close</button>

运行 下面的代码片段可以看到它的实际效果。

var div = document.getElementById("email3");
 
 function openEmail3(){
    if  (div.style.display === "none") {
    div.style.display = "block";
    }
    else {
    div.style.display === "none" }
  }
  
  function closeEmail3(){
    if  (div.style.display === "block") {
    div.style.display = "none";
    }
  }
<table>
<tr class="foo" onclick="openEmail1();">...</tr>
<tr class="foo" onclick="openEmail3();"> <!-- this opens fine-->
  <td>From: Me</td>
  <td>Subject: Why won't this work?</td>
  <td>Date:

  <div style="display: none" id="email3">..email popup..

    <div>...header box in email popup...</div>
    <div>...email body box in email popup...</div>
    <div>
      <button onclick="openForm();">Forward</button> <!-- this works fine-->
      <button onclick="closeEmail3();event.stopPropagation()">Close</button> <!-- does not work-->
    </div>

  </div>
  </td>
</tr>
</table>