javascript HTML中的Javascript增量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15280851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript increment value inside HTML
提问by pashaPear
I'm completely new to JavaScript. I'm trying to increment a variable inside the HTML, it's not working. Is my syntax wrong?
我对 JavaScript 完全陌生。我正在尝试在 HTML 中增加一个变量,但它不起作用。我的语法错了吗?
<script>
function rps() {
computerScore.value++;
computerScore.innerHTML = computerScore.value;
}
</script>
<html>
<b>computer score:</b><p id="computerScore" value="0">-</p>
<button type="button" onclick="rps()">Go</button><br>
</html>
回答by Adam Plocher
value
is not a valid attribute for the <p>
tag.
value
不是<p>
标签的有效属性。
I think you want something like:
我想你想要这样的东西:
function rps() {
var computerScore = document.getElementById('computerScore');
var number = computerScore.innerHTML;
number++;
computerScore.innerHTML = number;
}
...
...
<b>computer score:</b><p id="computerScore">0</p>
回答by Denys Séguret
A few problems :
几个问题:
- on most browsers, you can't get an element by id just as a global property
- an attribute isn't always a property of an element (the value is only a property of input elements)
- 在大多数浏览器上,您不能像全局属性一样通过 id 获取元素
- 属性并不总是元素的属性(值只是输入元素的属性)
You can do this :
你可以这样做 :
function rps() {
// fetch the element :
var element = document.getElementById('computerScore');
// get the attribute, parse it and increment it :
value = parseInt(element.getAttribute('value'), 10)+1;
// stores the incremented value :
element.setAttribute('value', value);
// and change the innerHTML (conversion to string is implicit)
element.innerHTML = value;
}
回答by Explosion Pills
A couple issues:
几个问题:
computerScore
is nothing; you probably wantdocument.getElementById('computerScore')
value
on a<p>
is not valid. Usedata-value
or something instead (or
computerScore
没什么; 你可能想要document.getElementById('computerScore')
value
在 a<p>
上无效。使用data-value
或代替(或
var computerScore = document.getElementById('computerScore');
function rps() {
computerScore.dataset.value++;
computerScore.innerHTML = computerScore.dataset.value;
}
Note that dataset.value
is a string, but the ++
coerces it to an integer.
请注意,这dataset.value
是一个字符串,但将其++
强制为整数。
I would also suggest using event bindings rather than event attributes, e.g. button.addEventLister
我还建议使用事件绑定而不是事件属性,例如 button.addEventLister
回答by Misterwyz
The best option will be to pass in an event object from the rps() method in the HtML, like this: rps(event).
Then retrieve it from the Javascript method like this:
function rps(event) {
var computerScore = event.CurrentTarget.innerText;
computerScore++;
computerScore = number;
}
回答by vsync
var elm = whatever //assuming you select your element using the DOM
// update value
elm.innerHTML = +elm.innerHTML + 1;