使用document.createElement()创建的按钮不会出现触发onclick事件

时间:2017-09-12 18:31:06

标签: javascript dom

This is my site(相关HTML的位置)。

我希望在视口低于或等于768px时切换主菜单。

我渴望只在vanilla JavaScript中这样做。

为此,我编写了以下算法和代码,它们运行在DOMContentLoaded:

  1. 如果视口小于或等于786px,请执行:
  2. 选择主菜单,然后选择display:none
  3. 创建一个按钮并给它一个类。
  4. 将按钮附加到({1}}的结尾。
  5. 单击按钮时,重新显示菜单。
  6. 我的代码:

    header

    执行中的控制台没有错误。

    我的问题:

    问题似乎是按钮没有被创建,即document.addEventListener('DOMContentLoaded', ()=>{ if (window.innerWidth <= 768) { let menu = document.querySelector(' #menu-mainmenu '); return menu.style.display = 'none'; let newButton = document.createElement('div'); newButton.className = 'menuButton'; let myHeader = document.querySelector('#masthead'); myHeader.appendChild(newButton); newButton.addEventListener('click', ()=>{ return menu.style.display = 'block'; }); } }); 方法失败(带有createElement()的{​​{1}}没有出现在DOM中)。为什么会这样?

3 个答案:

答案 0 :(得分:1)

let myHeader = document.querySelector('#masthead');

这应该是我们添加创建的元素吗?然而,这是一个小问题:网站还没有加载。我很惊讶,虽然你的代码看起来很好(wohoo,你使用let;))你没有注意到控制台中的错误(无法获得undefined的appendChild),你也没想过将所有内容包装在DOMContentListener中:

if (window.innerWidth <= 768) {
document.addEventListener('DOMContentLoaded', ()=>{
    let menu = document.querySelector(' #menu-mainmenu ');
    return menu.style.display = 'none';

    let newButton = document.createElement('div');
    newButton.className = 'menuButton';

    let myHeader = document.querySelector('#masthead');
    myHeader.appendChild(newButton);

    newButton.addEventListener('click', ()=>{
        return menu.style.display = 'block';
    });
});    
}

答案 1 :(得分:1)

    return menu.style.display = 'none';

    let newButton = document.createElement('div');

在创建元素之前的行上,您return

return立即结束该功能

不要回到那里。

但是,使用媒体查询可以更好地处理此类任务。

答案 2 :(得分:0)

为此你可以使用CSS Media Queries,我在下面添加了一个例子,你需要很少的jQuery代码才能做到这一点。

  

观察:我已经编辑了我的答案,现在它会在你点击按钮后显示主菜单。

&#13;
&#13;
function hideButtonAndShowMenu() {
// Hides button
  document.getElementsByClassName('mobile-button')[0].style.display = 'none'   
  document.getElementsByClassName('yourMainMenuClass')[0].classList.toggle('show')
}
&#13;
@media screen and (min-width: 769px) {
  .mobile-button {
    display: none;
  }
}
@media screen and (max-width: 768px) {
  .yourMainMenuClass:not(.show) {
    display: none;
  }
}
&#13;
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <input type='button' onclick="hideButtonAndShowMenu()" class='mobile-button' value="Don't click me please :-("> </input>
</header>

<div class='yourMainMenuClass'>
  <h2> If you are seeing this, you're not on the mobile View!</h2>
      <h3> Try resizing this window :-) </h3>
</div>
&#13;
&#13;
&#13;

相关问题