JavaScript事件处理程序出现问题

5

我希望这不会被标记为“重复”,因为我已经查看了几个线程并按照找到的建议进行了操作。我知道我错过了一些简单的东西,需要其他人来帮我看看。我是一个新手,请耐心等待。我正在测试一个简单的按钮元素,我在上面设置了一个点击事件处理器,但是它没有起作用。它可以通过“onclick”内联工作,但我想避免这种情况。这是简单的html代码:

<div>
    <button id='handler'>Event</button>
</div>
<div id='stringText'>
    <h4>Some Description</h4>
    <p>
        Some more information
    </p>
</div>

以下是JavaScript代码:

<script>
    document.getElementById("handler").addEventListener("click", display, true);
    function display() {

        if (document.getElementById("stringText").style.display === "block") {
            document.getElementById("stringText").style.display = "none";
        } else {
            document.getElementById("stringText").style.display = "block";
        }

    };

</script>

我有一段CSS代码,最初将“stringText”的显示设置为“none”。非常感谢任何帮助。


混合使用CSS和“style”属性是一件有趣的事情。请阅读此答案:https://stackoverflow.com/a/49289840/3662110 - jmargolisvt
这是一篇很好的文章,很有道理。我会改正我的做法,谢谢! - Pops Jones
3个回答

4
  • 很可能你的问题与文档加载时执行该脚本有关。
  • 添加条件stringText.style.display === ""可以正确显示/隐藏元素。

另一种选择是使用事件DOMContentLoaded

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
  document.getElementById("handler").addEventListener("click", display, true);

  function display() {
    var stringText = document.getElementById("stringText");
    if (stringText.style.display === "block" || stringText.style.display === "") {
      stringText.style.display = "none";
    } else {
      stringText.style.display = "block";
    }
  };
});
<div>
  <button id='handler'>Event</button>
</div>
<div id='stringText'>
  <h4>Some Description</h4>
  <p>
    Some more information
  </p>
</div>


2
请允许一些延迟来加载使用 window.onload 事件的页面。

<div>
    <button id='handler'>Event</button>
</div>
<div id='stringText'>
    <h4>Some Description</h4>
    <p>
        Some more information
    </p>
</div>

<script>
window.onload = function(){
 document.getElementById("handler").addEventListener("click", display, true);
};
   
    function display() {

        if (document.getElementById("stringText").style.display === "block") {
            document.getElementById("stringText").style.display = "none";
        } else {
            document.getElementById("stringText").style.display = "block";
        }

    };

</script>


已更新事件,请查看。 - I. Ahmed
运行得非常好!谢谢。@Ele,这个解决方案也很有帮助。非常感谢。 - Pops Jones

1
如果您确保并将初始显示属性设置为块,则可以正常工作。作为替代方案,您还可以尝试使用jQuery,就像我在片段中所做的那样。

//with jquery

$(document).ready(function() {
  $('#handler').on('click', function() {
    $('#stringText').toggleClass('hide');
  })
})
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button id='handler'>Event</button>
</div>
<div id='stringText'>
  <h4>Some Description</h4>
  <p>
    Some more information
  </p>
</div>


有一个JS事件可以捕获DOM加载完成的时刻,不需要使用jQuery。 - Ele

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接