javascript事件处理程序的问题

时间:2018-03-27 02:26:21

标签: javascript eventhandler

我希望这不会被标记为“重复”,因为我已经审查了几个主题并遵循了我发现的建议。我知道我错过了一些简单的东西,需要另外一些眼睛。我是新手,所以请耐心等待。我正在测试一个简单的按钮元素,我有一个单击事件处理程序,但它无法正常工作。它与“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”。我感谢任何协助。

3 个答案:

答案 0 :(得分:4)

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

另一种方法是使用 DOMContentLoaded

事件

&#13;
&#13;
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";
    }
  };
});
&#13;
<div>
  <button id='handler'>Event</button>
</div>
<div id='stringText'>
  <h4>Some Description</h4>
  <p>
    Some more information
  </p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

请允许延迟使用window.onload事件加载页面

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果你确定并将初始显示属性设置为阻止它可以正常工作。作为替代方案,您也可以尝试使用jQuery,就像我在代码段中一样。

&#13;
&#13;
//with jquery

$(document).ready(function() {
  $('#handler').on('click', function() {
    $('#stringText').toggleClass('hide');
  })
})
&#13;
.hide {
  display: none;
}
&#13;
<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>
&#13;
&#13;
&#13;