最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6 Display div to none when button is clicked - Stack Overflow

programmeradmin2浏览0评论

I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}
<div id="block">
  <button id="button" onClick="hide()">my button</button>
</div>

I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}
<div id="block">
  <button id="button" onClick="hide()">my button</button>
</div>

Any help please?

Share Improve this question edited Nov 14, 2017 at 11:43 3Dos 3,4973 gold badges26 silver badges39 bronze badges asked Nov 14, 2017 at 11:15 BeeLeeBeeLee 1935 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You are attaching an event handler for first time. After the second time it will work and will again attach an event handler.

You don't need to use inline event handler, avoid this type of event handler attachement. You can just remove the hide function part serving the content. When your code runs, it will attach the event handler

const z = document.getElementById('button');
const y = document.getElementById('block');

z.onclick = () => {
    y.style.display = 'none';
};
<div id="block">
  <button id="button">my button</button>
</div>

Instead of hiding the div, your hide method is assigning a new onclick handler to your button.

Simply

const hide = () => {
    document.getElementById('block').style.display='none'
  }
发布评论

评论列表(0)

  1. 暂无评论