我是Javascript的新手。我无法理解如何访问变量,以便我可以将它们输入到等式中并将答案输出回html。
html:
<body>
<div onclick="firstq(100)">100</div>
<div onclick="firstq(150)">150</div>
<div onclick="firstq(300)">300</div>
<div id="results"></div>
</body>
javascript:
function firstq(one) {
switch(one) {
case 100:
var answer1 = 100;
break;
case 150:
var answer1 = 150;
break;
case 300:
var answer1 = 300;
break;
}
document.getElementById("results").innerHTML="The total is = "+answer1;
}
直到这一点它才能正常工作并显示输出,但我真正想做的是根据不同的答案建立一个方程式,然后在点击另一个div之后输出它,某种方式类似于:
更多html:
<div onclick="secondq(5)">5</div>
<div onclick="secondq(10)">10</div>
<div onclick="secondq(20)">20</div>
<div id="thebutton" onclick="clickedthebutton()'>Click me!</div>
更多js:
function firstq(two) {
switch(two) {
case 5:
var answer2 = 5;
break;
case 10:
var answer2 = 10;
break;
case 20:
var answer2 = 20;
break;
}
}
function clickedthebutton() {
var theanswer = answer1*answer2;
document.getElementById("results").innerHTML="The total is = "+theanswer;
}
我不确定变量是否需要全局化,或者我忽视的是什么。
谢谢!
答案 0 :(得分:0)
在javascript标记内声明全局变量:
var answer1;
var asnwer2;
我在您的javascript代码
中看不到功能secondq(two)
答案 1 :(得分:0)
如果我理解你,你会想做这样的事情:
var calc = (function(){
var answer1 = 0,
answer2 = 0;
function firstq(one) {
answer1 = 300;
}
function secondq(two) {
answer2 = two;
}
function clickedthebutton() {
var theanswer = answer1*answer2;
document.getElementById("results").innerHTML="The total is = "+theanswer;
}
return {
firstq: firstq,
secondq: secondq,
clickedthebutton: clickedthebutton,
}
}());
<div onclick="calc.firstq(100)">100</div>
<div onclick="calc.firstq(150)">150</div>
<div onclick="calc.firstq(300)">300</div>
<div id="results"></div>
<div onclick="calc.secondq(5)">5</div>
<div onclick="calc.secondq(10)">10</div>
<div onclick="calc.secondq(20)">20</div>
<div id="thebutton" onclick="calc.clickedthebutton()'>Click me!</div>
不要使用html属性来注册点击事件。最好在JavaScript代码中附加您的活动;最重要的是,避免将许多变量引入全局范围