将HTML文本设置为JS变量

时间:2015-04-17 03:49:35

标签: javascript html variables text tags

我想从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>

我正在研究一个计算器,并希望从&#34;屏幕&#34;中获取值。并将它们保存到变量中,以便进行数学运算。在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并打印答案。

5 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

使用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;

答案 3 :(得分:0)

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);
}

答案 4 :(得分:0)

你想要那个形式吗?你可能想要这样的东西:

<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>