如何将Jquery合并到此代码中

How to incorporate Jquery in this code?

本文关键字:代码 合并 Jquery      更新时间:2023-09-26

我正试图在代码中使用Jquery创建一个计算器。我已经用javascript制作了一个功能强大的计算器,但我很难弄清楚如何将jquery融入其中

我仍然对如何更改代码感到困惑。我试过做一些事情,但每次尝试都无法得出正确的结果。请帮帮我!

<!doctype html>
<html>
<title>Jquery Calculator</title>
<h1> Basic Calculator</h1>
<script type="text/javascript">
     <!--
        var opr;
        function processOperator(name){
          opr = name;
          alert ("You selected " + opr);
        }
        function performCalculation (){
             var n1 = document.getElementById('num1').value;
             var n2 = document.getElementById('num2').value;
             var res;
             //Perform error checking
            if (opr == 'plus')
    {
        res = n1*1 +n2*1;
    }
    else if (opr == 'minus')
    {
        res = n1*1 - n2*1; 
    }
    else if (opr == 'times')
    {
        res= n1*1 * n2*1; 
    }
    else if (opr == 'divide')
    {
        res= n1*1 / n2*1;
    }
    else {
            alert ("Operator undefined. Please select a valid operator");
            res = 0;
        }
        document.getElementById('res').value = res;
        }
     //-->
  </script>
<fieldset>
<label for="first">Number 1:</label>
<input id="num1" type="number" name="first">
<br>
<label for="second">Number 2:</label>
<input id="num2" type="number" name="second">
<br>
<label for="result">Result:</label>
<input id="res" type="number" name="result">
<br>

<img src="math_symbols_0.jpg" alt="" usemap="#map" />
<map name="map">
<area shape="rect" coords="73, 231, 219, 299"
      onClick="performCalculation('total')"/>
<area shape="rect" coords="162, 117, 298, 222"
      onClick="processOperator('divide')"/>
<area shape="rect" coords="1, 143, 135, 198"
      onClick="processOperator('minus')"/>
<area shape="rect" coords="175, 2, 298, 99"
      onClick="processOperator('times')"/>
<area shape="rect" coords="0, 0, 137, 104"
      onClick="processOperator('plus')"/>
</map>

</fieldset>

<script>
function myfunc()
{
    var text;

    var n1 = document.getElementById('num1').value;
    var n2 = document.getElementById('num2').value;

    if (isNaN(n1) || isNaN(n2)) {
        text = "Input not valid";
        alert (text);
    }  
    // Perform another input validation test
    else if(0)
    {
    }
    // All checks pass.. Do the calculation
    else{
        var res = n1*1 + n2*1;
    //document.write(res);
        var result = "<h3> Result is: " + res + "</h3>";
    //document.getElementsByName('result')[0].value = res;
        document.getElementById('res').value = res;
    }
} 
</script>
</html>

我会用一个id来标记每个按钮,比如divideadd

现在你可以说:

res=$('#res')
$(divide).click(function(){
    $('#res').html($('#num1').html()*1 / $('#num2').html()*1);
});

您可以对每个按钮重复此操作。