【问题标题】:Javascript, Two actions in One button by IF [duplicate]Javascript,IF的一个按钮中的两个动作[重复]
【发布时间】:2020-11-06 08:38:00
【问题描述】:

这很简单。
我想一键更改框的颜色。
这个'if'函数有什么问题?

<body>
    <div class="box" style="width: 50px; height: 50px; background: brown;"></div>
    <button class="btn" value="brown">Color Change</button>
</body>

<script>
    btn = document.querySelector('.btn');
    box = document.querySelector('.box');

    btn.addEventListener('click', () => {
        if (box.style.backgroundColor = 'brown'){
            box.style.backgroundColor = 'black';            
        } else{
            box.style.backgroundColor = 'brown';
        }
    })
</script>

【问题讨论】:

  • =if 子句中赋值而不是比较===

标签: javascript button addeventlistener


【解决方案1】:

检查一下:

  btn = document.querySelector('.btn');
    box = document.querySelector('.box');

    btn.addEventListener('click', () => {
        if (box.style.backgroundColor == 'brown'){
            box.style.backgroundColor = 'black';            
        } else{
            box.style.backgroundColor = 'brown';
        }
    })
  <div class="box" style="width: 50px; height: 50px; background: brown;"></div>
   <button class="btn" value="brown">Color Change</button>

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2014-04-11
    • 2014-10-08
    • 2020-04-08
    相关资源
    最近更新 更多