怎么用JS 写一个四则运算

怎么用JS 写一个四则运算,第1张

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>computer</title>

<script>

function compute(){

str1=Number(document.getElementById("txt1").value)

str2=Number(document.getElementById("txt2").value)

comp=document.getElementById("select").value

var result

switch(comp) {

case "+":

comp=str1+str2

break

case "-":

comp=str1-str2

break

case "*":

comp=str1*str2

break

case "/":

if(str2==0){

alert("除数能为0!")

comp=''

}else{

comp=str1/str2

}

break

}

document.getElementById("result").value=comp

}

</script>

</head>

<body>

<input type="text" id="txt1"/>

<select name="method" id="select">

<option value="+">+</option>

<option value="-">-</option>

<option value="*">*</option>

<option value="/">/</option>

</select>

<input type="text" id="txt2"/>

<input type="button" id="b1" value="等于" onclick="compute()" />

<input type="text" id="result"/>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title></title>

</head>

<body>

<table>

<tr>

<td><input type="button" value="add" onclick="setOp('+', 'add')"/></td>

<td><input type="button" value="miner" onclick="setOp('-', 'miner')"/></td>

<td><input type="button" value="times" onclick="setOp('*', 'times')"/></td>

<td><input type="button" value="divide" onclick="setOp('/', 'divide')"/></td>

</tr>

</table>

<table id="tb_calc" style="display:none">

<tr>

<td><input id="x" type="text" style="width:100px" value="" name="x" /></td>

<td><lable id="op" name="op"></lable></td>

<td><input id="y" type="text" style="width:100px" value="" name="y" /></td>

<td><input id="opTips" type="button" value="" onclick="calc()"/></td>

<td><lable id="z" name="z"></lable></td>

</tr>

</table>

<script type="application/javascript">

function setOp(op, opTips)

{

var tb=document.getElementById("tb_calc")

tb.style.display = "none"

document.getElementById("x").value = ""

document.getElementById("y").value = ""

document.getElementById("z").innerText = ""

document.getElementById("op").innerText = op

document.getElementById("opTips").value = opTips

tb.style.display = "block"

}

function calc()

{

var x = parseInt(document.getElementById("x").value)

var y = parseInt(document.getElementById("y").value)

var op = document.getElementById("op").innerText

var z = ""

switch(op)

{

case '+':

z = x + y

break

case '-':

z = x - y

break

case '*':

z = x * y

break

case '/':

z = x / y

break

default:

z = ''

}

console.log(x, op, y, '=', z)

document.getElementById("z").innerText = z

}

</script>

</body>

</html>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/7004224.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-31
下一篇 2023-03-31

发表评论

登录后才能评论

评论列表(0条)

保存