簡體   English   中英

如何使用JavaScript加,減或乘兩個變量?

[英]How can I add, subtract, or multiply two variables using JavaScript?

<!DOCTYPE html>
<head><title> test ! </title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>
<html>
<body>

<div class="container">

first number : <input class="form-control" id="num1" />
<br>
second number : <input class="form-control" id="num2" />
<br>
<select id="mathtype">
   <option value="add"> addition </option>
   <option value="sub"> subtraction </option>
   <option value="mul"> multiplication </option>
</select>
<br><br>
<button class="btn btn-primary" onclick="submit()" > submit </button>
<br><br>
<input type="text" id="output" >

</div>



</body>
<script src="js/jquery-1.9.1.js"></script>
<script>

function submit(){

    var mathtype = document.getElementById['mathtype'];

    if (mathtype == add ) {
        return num1 + num2;
    } else if (mathtype == sub ) {
        return num1 - num2;
    } else if (mathtype == mul ) {
        return num1 * num2;
    }   

    return true;

}

</script>

</html>

我目前的錯誤:

SyntaxError:函數語句需要一個名稱。

我想制作一個程序,該程序將根據所選的值(add,sub,mul)執行數學運算,然后單擊Submit,答案顯示在輸入中,其ID為“輸出”。

 function submit() { var mathtype = document.getElementById('mathtype').value; //Get the value of the select element..Correct the typo([]) var num1 = Number(document.getElementById('num1').value); //Get the value of `num1` input and convert it to type `Number` var num2 = Number(document.getElementById('num2').value); //Get the value of `num2` input and convert it to type `Number` if (mathtype == 'add') { //Compare with `string` as value of select input will be of type string, you did not have variable `add` to be tested document.getElementById('output').value = num1 + num2; } else if (mathtype == 'sub') { //Compare with `string` as value of select input will be of type string, you did not have variable `sub` to be tested document.getElementById('output').value = num1 - num2; } else if (mathtype == 'mul') { //Compare with `string` as value of select input will be of type string, you did not have variable `mul` to be tested document.getElementById('output').value = num1 * num2; } } 
 <div class="container"> first number : <input class="form-control" id="num1" /> <br>second number : <input class="form-control" id="num2" /> <br> <select id="mathtype"> <option value="add">addition</option> <option value="sub">subtraction</option> <option value="mul">multiplication</option> </select> <br> <br> <button class="btn btn-primary" onclick="submit()">submit</button> <br> <br> <input type="text" id="output"> </div> 

注意 :瀏覽注釋以獲取詳細說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM