简体   繁体   English

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

[英]How do I make a JAVASCRIPT variable equal to an HTML attribute?

I am basically trying to have a number displayed that starts at 0 and goes up randomly every time you press a button. 我基本上是想显示一个从0开始并在您每次按下按钮时随机上升的数字。 But I need a variable to equal the current number(which is stored within an h1 tag). 但是我需要一个变量来等于当前数字(存储在h1标签中)。 How do I do that? 我怎么做? Currently when I try to check if it worked by alerting the page, all I get is [object HtmlHeadingElement] Here is my JavaScript, CSS, and HTML code, respectively: 当前,当我尝试通过警告页面来检查它是否有效时,我得到的只是[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> 

You could get the html content using innerHTML. 您可以使用innerHTML获取html内容。 See below, 见下文,

 function myRandom() { var headnumber = document.getElementById('headnum').innerHTML; 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> 

The assignment of headnumber is to an object returned by the document.getElementById('headnum') function call. headnumber的分配是由document.getElementById('headnum')函数调用返回的对象。 In order to get the value inside the object use document.getElementById('headnum').innerHTML 为了获取对象内部的值,请使用document.getElementById('headnum').innerHTML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM