使用javascript的计算器功能

时间:2015-11-20 13:06:22

标签: javascript

我试图通过接受来自文本框的输入来执行算术计算,这取决于应该执行操作员各自的操作。我正在尝试为逻辑和视图编写单独的函数。我很难解决什么问题!

[1]: http://plnkr.co/edit/9cyKKbPC0xYmp1qf1u7G?p=preview 

3 个答案:

答案 0 :(得分:1)

<!DOCTYPE html> 
<html lang="en-US"> 
<head>
<meta charset="utf-8">
<title>Assignment</title>  
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
<div id="main">
<div class="first"> 
Num1:<input type="text" value="0" id="first" class="box1"><br>
Num2:<input type="text" value="0" id="second" class="box1">
<a class="btn" href="javascript:;">Calcule!</a>
</div>

<div class="second">
Op:<input type="text" value="+" id="oper"  class="box2">
</div>
<div id="result"></div>

<div  class="third">
<span id="demo">Sum:0.00</span>
</div>
</div>
<script src="script.js"></script>
</body> 
</html> 

我使用jQuery

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function(){
    //You can captured value
    //With # you capture the ID element, with . you capture the class element
    //First you need a button for calculate
    $('.btn').on("click",function(){
        var first_number = $('#first').val(); 
        var second_number = $('#second').val(); 
        var result = parseInt(first_number)+parseInt(second_number);
        alert(result);
        //You also can add an HTML element with the result
        $('#result').html("The result is "+result);
        //OR in your result
        $('#demo').html("Sum: "+result);

    });
});

现在,您需要为每个操作提供逻辑。

答案 1 :(得分:0)

您可以更改

function calculation() {

function calculation(x, y, z) {

答案 2 :(得分:0)

首先,您需要确定何时执行该功能,您是否有任何按钮来触发该动作?

我在这里给你一些javascript代码,它们可以在触发器操作调用的任何函数中运行:

 function calculate() {
    var num1 = document.getElementById("first").value;
    var num2 = document.getElementById("second").value;
    var operation = document.getElementById("oper").value;

    if(operation == "+")
        return parseFloat(num1)+parseFloat(num2);
    if(operation == "-")
        return parseFloat(num1)-parseFloat(num2);
    if(operation == "*")
        return parseFloat(num1)*parseFloat(num2);
    if(operation == "/")
        return parseFloat(num1)/parseFloat(num2);
}

您可以查看我在此处工作的示例: http://plnkr.co/edit/uTmSD1XWJwSYxbBqyct7?p=preview