如何使JAVASCRIPT变量等于HTML属性?

时间:2016-04-19 23:11:33

标签: javascript jquery html css

我基本上试图显示一个从0开始的数字,每按一次按钮就会随机上升。但我需要一个变量来等于当前的数字(存储在一个h1标签中)。我怎么做?目前,当我尝试通过警告页面来检查它是否有效时,我得到的只是 [object HtmlHeadingElement]这是我的JavaScript,CSS和HTML代码:



function myRandom() {
  var headnumber = document.getElementById('headnum');
  alert(headnumber)
    //the alert is just to check if '0' comes up'
}

 

h1 {
  text-align: center;
  font-size: 30px;
  color: blue;
  font-family: Verdana;
}
button {
  margin-left: 640px;
  border: solid blue 5px;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  background-color: cyan;
  border-radius: 6px;
}

<h1 id='headnum'>3</h1>
<button onclick="myRandom()">Button</button>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

您可以使用innerHTML获取html内容。见下文,

&#13;
&#13;
function myRandom() {
  var headnumber = document.getElementById('headnum').innerHTML;
  alert(headnumber)
    //the alert is just to check if '0' comes up'
}
&#13;
h1 {
  text-align: center;
  font-size: 30px;
  color: blue;
  font-family: Verdana;
}
button {
  margin-left: 640px;
  border: solid blue 5px;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  background-color: cyan;
  border-radius: 6px;
}
&#13;
<h1 id='headnum'>3</h1>
<button onclick="myRandom()">Button</button>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

headnumber的赋值是document.getElementById('headnum')函数调用返回的对象。要获取对象内的值,请使用document.getElementById('headnum').innerHTML