简体   繁体   English

有人可以帮我实现按钮功能吗?

[英]Can someone help me with my button functions?

When I press the minus button on the left, I would like for the number on the left side of the equals sign (in this case "7") to count down one number for each button click until it reaches zero. 当我按下左侧的减号按钮时,我希望等号左侧的数字(在本例中为“ 7”)为每次单击的按钮递减一个数字,直到达到零为止。

I have html, css, and js files working together. 我有html,css和js文件一起工作。 I put them into one file and cut out any unnecessary code for the purpose of posting here. 我将它们放到一个文件中,并切出任何不必要的代码,以便在此处发布。 My problem is (I think) in the function leftMinusButton() and how it communicates with the html. 我的问题是(我认为)函数leftMinusButton()及其与html的通信方式。

 function leftMinusButton() { var i = document.getElementById("leftnum"); if (i > 0) { i--; } } 
 body { font-family: arial, "times new roman"; background: lightblue; color: black; text-align: center; } .leftminus { position: absolute; top: 60px; left: 30px; width: 50px; height: 50px; font-size: 40px; } .variable { position: absolute; top: 120px; left: 115px; font-size: 40px; } .plus { position: absolute; top: 120px; left: 175px; font-size: 40px; } .leftnum { position: absolute; top: 120px; left: 240px; font-size: 40px; } .equals { position: absolute; top: 120px; left: 300px; font-size: 40px; } .rightnum { position: absolute; top: 120px; left: 350px; font-size: 40px; } 
 <div id="workspace"> <div class="variable" id="variable">x</div> <div class="plus" id="plus">+</div> <div class="leftnum" id="leftnum">7</div> <div class="equals" id="equals">=</div> <div class="rightnum" id="rightnum">19</div> </div> <div id="plusminus"> <button type="button" class="leftminus" id="leftminus" onclick="leftMinusButton()">-</button> </div> 

You would need to set the new value of i back to the element "leftnum". 您需要将i的新值重新设置为元素“ leftnum”。 Also, for getting the value of the element "leftnum" you need to access the innerHTML property. 另外,为了获取元素“ leftnum”的值,您需要访问innerHTML属性。

var i = document.getElementById("leftnum");
var value = parseInt(i.innerHTML);
if (value  > 0) {
    value--;
}
i.innerHTML = value;

document.getElementById() will only get you the DOM node, you then need to get the value from it (innerHTML), do whatever you need to do, then set the result. document.getElementById()仅会为您提供DOM节点,然后您需要从中获取值(innerHTML),执行所需的任何操作,然后设置结果。 May I suggest you have a look at innerHTML - https://www.w3schools.com/jsref/prop_html_innerhtml.asp for how to get the value, and how it can be set 我可以建议您看看innerHTML - https : innerHTML如何获取值以及如何设置它

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

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