我有三个标签。我想减去两个标签并将结果放在第三个标签中。
$(document).ready(function() {
//Get the texts from both textboxes
var txt1 = document.getElementById("addition").value;
var txt2 = document.getElementById("investplan").value;
//Substract that
var res = parseInt(txt1) - parseInt(txt2);
//Set the value to your div
document.getElementById("subtraction").innerHtml = res;
});
<label id="investplan">23940</label>
<label id="addition">138790</label>
<label id="subtraction"></label>
答案 0 :(得分:1)
一些提示:
您将 jQuery 和纯 javascript 混为一谈。 $(document).ready()
是 jQuery - 您必须包含 jQuery 库。我替换了纯 JS 等价物。另外 .val()
是您在 jQuery 中读取值的方式(这可能是您对 .value
的想法),而在纯 JS 中,您可能想要 .innerText
或 .textContent
或.innerHTML
是.innerHTML
不是.innerHtml
使用 Div 或 Span 代替标签标签。 label 标签旨在将可点击控件(例如单选按钮)与一些附加文本组合在一起,以便点击文本触发单选按钮控件。
document.addEventListener('DOMContentLoaded',() => {
//Get the texts from both textboxes
var txt1 = document.getElementById("addition").innerText;
var txt2 = document.getElementById("investplan").innerText;
console.log(txt1);
//Substract that
var res = parseInt(txt1) - parseInt(txt2);
console.log(res);
//Set the value to your div
document.getElementById("subtraction").innerHTML = res;
});
<label id="investplan">23940</label>
<label id="addition">138790</label>
<label id="subtraction"></label>
参考:
https://www.javascripttutorial.net/javascript-dom/javascript-page-load-events/
答案 1 :(得分:0)
使用textContent property。代码应该是:
$(document).ready(function() {
//Get the texts from both textboxes
var txt1 = document.getElementById("addition").textContent;
var txt2 = document.getElementById("investplan").textContent;
//Substract that
var res = parseInt(txt1) - parseInt(txt2);
//Set the value to your div
document.getElementById("subtraction").innerHTML = res;
})