[英]How can i get the text of a paragraph and then turn it into an integer in HTML
I have a simple paragraph as: <p id="amt1">0</p>
and have a button called to add to the amount as: <button id="addbtn1">+</button>
I want it such that when i press the button the text in the paragraph is updated to 1 and after pressing it again is updated to two 我有一个简单的段落:
<p id="amt1">0</p>
并有一个按钮被调用以添加到金额中: <button id="addbtn1">+</button>
当我按下按钮时,段落中的文本更新为1,再次按下后更新为2
Any help would be great! 任何帮助将是巨大的! Thanks!
谢谢!
http://codepen.io/anon/pen/JGxvZg http://codepen.io/anon/pen/JGxvZg
$('#plus').click(function(){
var x = Number($('#result').html());
$('#result').html(x+1);
});
var txtNode = document.querySelector('#number');
var btn = document.querySelector('#btn');
var count = 0;
btn.addEventListener('click', function() {
txtNode.innerHTML = 'Number: ' + count++;
}, false);
Basically you create a button/input element for the button, and ap tag (or whatever element you want to hold the number) and save both elements into variables using querySelector (or any other getter). 基本上,您为按钮创建一个按钮/输入元素,并创建ap标签(或任何您想要保留数字的元素),然后使用querySelector(或任何其他getter)将这两个元素保存到变量中。
Then what I did was initialized a counter variable. 然后我做了一个初始化计数器变量。
Next, I added what's called an EventListener to the button element. 接下来,我在按钮元素中添加了所谓的EventListener。 These are used to perform events, so when you click, whatever function is passed will execute on click.
它们用于执行事件,因此当您单击时,传递的任何功能都将在单击时执行。 Here I just set the p tag's innerHTML to the counter variable with the ++ operator after (means +1).
在这里,我只是在(表示+1)之后使用++运算符将p标签的innerHTML设置为计数器变量。 And every time you click it adds 1 to the counter variable.
每次单击时,它会将1加到计数器变量中。
hope this helps. 希望这可以帮助。
here's a JSBIN: http://jsbin.com/puxefaxuki/edit?js,console,output 这是一个JSBIN: http ://jsbin.com/puxefaxuki/edit?js,控制台,输出
Html: HTML:
<p id="counter">0</p>
<button id="add">Add</button>
Javascript (remove comments for the code to work out of the fiddle): Javascript(删除注释,使代码不再起作用):
//onload = function() {
counter = document.getElementById('counter')
add = document.getElementById('add')
add.onclick = function() {
counter.innerHTML = counter.innerHTML-0 +1
}
//}
Fiddle: https://jsfiddle.net/grabantot/o9v1cw7L/ 小提琴: https : //jsfiddle.net/grabantot/o9v1cw7L/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.