用js 寫計算機

來源:互聯網
上載者:User

標籤:js   計算機   代碼   

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<meta http-equiv = "content-type" content="text/html;charset=utf-8"/>

<script src="js.js" type="text/javascript" language="javascript">

</script>

</head>

<body>

<form>

<input type="button" value="1" onclick = "cal(this.value);"/> <!--調用函數-->

<input type="button" value="2" onclick = "cal(this.value);"/>

<input type="button" value="3" onclick = "cal(this.value);"/>

<input type="button" value="4" onclick = "cal(this.value);"/>

<input type="button" value="+" onclick = "cal(this.value);"/>

<input type="button" value="-" onclick = "cal(this.value);"/>

<input type="button" value="*" onclick = "cal(this.value);"/>

<input type="button" value="/" onclick = "cal(this.value);"/>

<input type="button" value="=" onclick = "cal(this.value);"/><br />

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

</form>

</body>

</html>

///js.js

function cal(value){var text = document.getElementById("text").value;var last = text.charAt(text.length-1);// 獲得文字框中的最後一個元素  if(text == null){text = "";    }else{if((value == "+")||(value == "-")||(value == "*")||(value == "/")){//輸入的是 + - / *if((last == "+")||(last == "-")||(last == "*")||(last == "/")){//文字框中的最後一個元素是 + - * / 在輸入 + - / * 時提示出錯alert("輸入不正確");}else{//文字框中的最後一個元素是 + - * / 再輸入數字時會添加到後面text += value;}}else if(value == "="){//輸入的是=   if((last == "+")||(last == "-")||(last == "*")||(last == "/")){//輸入的是=  , 當最後一個元素是+ - * / 時, 不能計算 ,只顯示除最後符號號的數text = text.substring(0,text.length-1);  }else{//輸入的是=   最後一個是數字  可以計算text = eval(text);  ///使用eval(str) 計算  }}else{//輸入的是數字  直接顯示text += value;}}document.getElementById("text").value = text; //將最後結果返回給文字框}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.