如何在这段代码中加入Jquery?

时间:2015-11-16 22:44:31

标签: javascript jquery imagemap

我正在尝试在我的代码中使用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>

1 个答案:

答案 0 :(得分:0)

我会使用ID标记每个按钮,例如divideadd

现在你可以说:

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

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