我的下面的代码工作正常,但我想知道,是否有任何仅通过 JavaScript 完成相同工作的简短方法?
<lable for="fstValue"></lable> First number is: <input type="text" id="fstValue" value="" />
<lable for="sndValue"></lable> Second number is: <input type="text" id="sndValue" value="" />
<hr>
<div id="showResult1"></div>
<div id="showResult2"></div>
<div id="showResult3"></div>
<div id="showResult4"></div>
<button onclick="sandeep()">Check Result</button>
//获取值,计算并显示值
function sandeep(){
// Define local function - sandeep varriable
var a, b, resPlus, resMinus, resMultiple, resDivide;
// Get First & Second value
a = parseInt(document.getElementById("fstValue").value);
b = parseInt(document.getElementById("sndValue").value);
// Do calculation
resPlus = a + b;
resMinus = a - b;
resMultiple = a * b;
resDivide = a % b;
// Show result
document.getElementById("showResult1").innerHTML="Plus is " + resPlus;
document.getElementById("showResult2").innerHTML="Minus is " + resMinus;
document.getElementById("showResult3").innerHTML="Multiple is " + resMultiple;
document.getElementById("showResult4").innerHTML="Divide is " + resDivide;
}
最佳答案
当然可以阵列驱动它。请注意我对 parseInt(*, 10)
的起诉,这很重要。
var a = parseInt(document.getElementById("fstValue").value, 10);
var b = parseInt(document.getElementById("sndValue").value, 10);
var texts = ["Plus", "Minus", "Multiple", "Divide"];
var results = [a + b, a - b, a * b, a / b];
for(var i = 0; i < 4; i++ ) {
document.getElementById("showResult" + (i+1) + ").innerHTML=" texts[i] + " is " + results[i];
}
请注意,您正在发现 Angular.js 等框架和其他所有框架都试图解决的问题。请注意以下是伪代码。如果您有 HTML 模板片段肯定会更好
<p>{text} is {result}</p>
你可以把它放在一个循环中
{{iterate over results object}}
<p>{result.text} is {result.results}</p>
{{ end iterate}}
现在 Javascript 中的工作要少得多。但更重要的是,应该在 HTML 中发生的工作现在发生在 HTML 中(数据布局),而在 JS 中发生的工作也应该发生在 JS 中(获取数据)。这是最先进的理论。
关于JavaScript getElementByID 有什么简短的方法可以完成相同的工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608381/