将 HTML 文本设置为 JS 变量

Setting HTML text to a JS variable

我想从 html 标签中获取文本并将其保存在 js 变量中。我看的是这个:

JavaScript:

function Myfunction(){
  var x; //Fist num here
  var y; //second num here
  var z=x+y;
  alert(z);
}

HTML:

<p id="num1">2</p>
<p id="num2">3</p>

我正在研究计算器,想从 "screen" 中获取值并将它们保存到一个变量中,以便进行数学运算。每个数字在 calc 程序中是这样分隔的:

<samp id="numb1">Any Number</samp><samp id="op">(+,-,*,/)</samp><samp id="numb2">Any Number</samp><samp id="answer">Answer prints here</samp>

将答案保存到变量后,numb1、op 和 numb2 将被清除并打印答案。

var x = document.getElementById('numb1').innerHTML;
var y = document.getElementById('numb2').innerHTML;
document.getElementById('answer').innerHTML = parseInt(x,10) + parseInt(y,10);
<samp id="numb1">2</samp>
<samp id="op">(+,-,*,/)</samp>
<samp id="numb2">3</samp>
<samp id="answer"></samp>

您可以像这样访问节点内容并存储变量:

var vAnswer = document.getElementById("answer").innerHTML;

使用jquery,可以得到如下图的值,

var x = $('#numb1').text();
var y = $('#numb2').text();
var z  =parseInt(x,10) +parseInt(y,10);
$('#answer').text('Total:'+z)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<samp id="numb1">2</samp>
<samp id="op">(+,-,*,/)</samp>
<samp id="numb2">3</samp>
<samp id="answer"></samp>

单独使用javascript,使用var x = document.getElementById('numb1').innerHTML;

function myFunction(){
  var x; //Fist num here
var y; //second num here
    x = $("#num1").text();
    y = $("#num2").text();
    alert(x);
    alert(y);
var z=parseInt(x,10)+parseInt(y,10);
alert(z);
}

你希望它成为一个表格吗?你可能想要这样的东西:

<html>
    <head>
        <script>
            function calc() {
                var leftInput = document.getElementById("left"),
                    left = parseInt(leftInput.value, 10),
                    operatorSelect = document.getElementById("operator"),
                    operator = operatorSelect.options[operatorSelect.selectedIndex].value,
                    rightInput = document.getElementById("right"),
                    right = parseInt(rightInput.value, 10),
                    expression = left + operator + right,
                    resultSpan = document.getElementById("result");
                resultSpan.innerHTML = eval(expression);
                leftInput.value = '';
                rightInput.value = '';
            }
        </script>
    </head>
    <body>
        <form>
            <input type="text" id="left">
            <select id="operator">
                <option value="+">+</option>
                <option value="-">-</option>
                <option value="*">*</option>
                <option value="/">/</option>
            </select>
            <input type="text" id="right">
            <input type="button" onclick="calc()" value="=">
            <span id="result"></span>
        </form>
    </body>
</html>