日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

jquery實現計算器小功能_jquery

作者:lunaticCode1 ? 更新時間: 2022-09-14 編程語言

本文實例為大家分享了jquery實現計算器功能的具體代碼,供大家參考,具體內容如下

用jquery實現計算器對于我來說有三個難點

1.單純的html頁面,怎么實現計算
2.顯示屏用什么標簽,又怎么把他顯示出來
3.要想實現刪除,怎么把字符串最后一個字母刪除

解決

1.看了別人的計算器,我發現eval()可以實現這個目的
eg: alert(eval(“3+5”));
沒錯,會彈出 8。
2.看了幾個人的博客,都是用span元素節點當顯示屏,通過jQuery的html()函數來實現把內容顯示出來。
3.有兩個思路,

一個是利用正則表達式,不過很多像我這樣的小白可能不會,我雖然學過,不過也差不多忘記了很多。
小姐姐告訴我,js文件中也可以用subString();

需要注意的地方

1.在html代碼中“<div id=“cal” οnclick=“f(event)>”
也就是說只要點擊這個div,它就會響應f(event)這個函數,這個函數定義在 js 代碼中。
2. 在js代碼function f(event){}中,this!= event.target;this表示的是id為cal的那個div的對象,event.target表示的是這個div的子級對象,比如點擊這個div的子級標簽,eg:value="D"的input元素標簽,那么event.target就為這個子級標簽的對象

html代碼

<!DOCTYPE html>
<html>
?<head>
? <meta charset="utf-8" />
? <title>計算器</title>
? <link  type="text/css" href="css/cal.css" />
? <script type="text/javascript" src="jquery-1.7.2.js">
? </script>
? <script type="text/javascript" src="js/cal.js" ></script>
?</head>
?<body>
? <div id="cal" onclick="f(event)">
? ?<span id="screen"></span>
? ? ? ? ?<input type="button" value="D" />
? ?
? ? ? <input type="button" value="7" />
? ? ? <input type="button" value="8" />
? ? ? <input type="button" value="9" />
? ? ? <input type="button" value="+" />
??
? ? ? <input type="button" value="4" />
? ? ? <input type="button" value="5" />
? ? ? <input type="button" value="6" />
? ? ? <input type="button" value="-" />
? ? ??
? ? ? <input type="button" value="1" />
? ? ? <input type="button" value="2" />
? ? ? <input type="button" value="3" />
? ? ? <input type="button" value="*" />
? ? ??
? ? ? <input type="button" value="0" />
? ? ? <input type="button" value="." />
? ? ? <input type="button" value="=" />
? ? ? <input type="button" value="/" />
? </div>
?</body>
</html>

css代碼

*{
?margin: 0px;
?padding: 0px;
}
#cal{
?width: 300px;
?border: 4px solid black;
?margin: 50px auto;
}
#screen{
?line-height:46px;
?text-indent: 10px;
?float: left;
?margin: 10px 10px;
?width: 196px;
?height: 46px;
?border: 2px solid;
?
}
input{
?margin: 10px;
?height: 50px;
?width: 50px;
?background-color: honeydew;
}
input:active{
?background: red;
}

js代碼

var clear=false;
function f(event){
?var btn=event.target;
?var $screen=$("#screen");
?var temp=$screen.html();
?var value=$(btn).val();
?//將除INPUT對象全部返回
? if($(btn).prop("nodeName")!="INPUT"){
? return;
? }
? //判斷是否需要清除屏幕
? if(clear==true){
? temp="";
? clear=false;
? }
? //刪除操作
? if(value=="D"){
? ?temp=temp.substring(0,temp.length-1);
? $screen.html(temp);
? }
? //點擊等于號時
? else if(value=="="){
? ?var result="="+eval(temp);
? ?$screen.html(temp+result);
? ?clear=true;
? }
? //點擊其他按鈕時
? else{
? ?temp=temp+value;
? ?$screen.html(temp);
? }
??
}

效果展示

原文鏈接:https://blog.csdn.net/lunaticCode1/article/details/93506330

欄目分類
最近更新