为什么我单击按钮我的标题不会改变?

时间:2017-03-27 12:43:52

标签: javascript events

我知道这应该是相当容易的,并且由于一些奇怪的原因,除了这个之外所有功能都有效。我没有看到任何可能做错的事情,以防止onClick事件将标题更改为蓝色。有人可以告诉我我做错了吗?

这是jfiddle: https://jsfiddle.net/CheckLife/680dvv5j/13/



#change {
  color: red;
}

<h1 id="change">NBA Legends</h1>
<button onclick="changedColor()">About</button>
<script>
  document.getElementById('change').onclick = changeColor;

  function changeColor() {
    document.body.style.color = "blue";
    return false;
  }
</script>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

如果您将样式应用于正文,它将为overriden,因为element具有自己的样式。

因此,将样式添加到元素中。

document.body.style.color更改为document.getElementById('change').style.color

见下文

document.getElementById('change').onclick = changeColor;

function changeColor() {
  document.getElementById('change').style.color = "#00f";
  return false;
}
#change {
  color:red;
}
<h1 id="change">NBA Legends</h1>

<button onclick="changeColor()">About</button>

答案 1 :(得分:0)

你有错字

<button onclick="changeColor()">About</button>

而不是

<button onclick="changedColor()">About</button>

答案 2 :(得分:0)

button点击功能名称changedColor更改为changeColor

&#13;
&#13;
  document.getElementById('change').onclick = changeColor;   

  function changeColor() {
      var element = document.getElementById('change')
      element.style.color = "blue";
      return false;
  }   
&#13;
#change {
  color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="change">NBA Legends</h1>

<button onclick="changeColor()">About</button>
&#13;
&#13;
&#13;