前言
今天学习了html,css,javascript的一些基础知识
简单实现一个计算器的基本功能
- 加
- 减
- 乘
- 除
- 清零
以下是本篇文章正文内容,下面案例可供参考
通过jQuery实现计算器功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算器</title>
<script src="jquery-1.9.1.min.js"></script>
<script>
function calc(type) {
var inputNum1 = jQuery("#num1");
var inputNum2 = jQuery("#num2");
if(type==1){
if (inputNum1.val()=="") {
alert("请先输入数字1");
return false;
}
if (inputNum2.val()=="") {
alert("请先输入数字2");
return false;
}
// 加法
var total = parseInt(inputNum1.val()) + parseInt(inputNum2.val());
//jQuery("#resultDiv").html(
// "<h2>计算相加的结果为:<strong style='color: chocolate;'>" + total + "</strong></h2>");
jQuery("#resultDiv")[0].innerHTML=
"<h2>计算相加的结果为:<strong style='color: chocolate;'>" + total + "</strong></h2>";
}
else if(type==2){
if (inputNum1.val()=="") {
alert("请先输入数字1");
return false;
}
if (inputNum2.val()=="") {
alert("请先输入数字2");
return false;
}
// 减法
var total = parseInt(inputNum1.val()) - parseInt(inputNum2.val());
jQuery("#resultDiv")[0].innerHTML=
"<h2>计算相减的结果为:<strong style='color: chocolate;'>" + total + "</strong></h2>";
}
else if(type==3){
if (inputNum1.val()=="") {
alert("请先输入数字1");
return false;
}
if (inputNum2.val()=="") {
alert("请先输入数字2");
return false;
}
// 乘法
var total = parseInt(inputNum1.val()) * parseInt(inputNum2.val());
jQuery("#resultDiv")[0].innerHTML=
"<h2>计算相乘的结果为:<strong style='color: chocolate;'>" + total + "</strong></h2>";
}
else if(type==4){
if (inputNum1.val()=="") {
alert("请先输入数字1");
return false;
}
if (inputNum2.val()=="") {
alert("请先输入数字2");
return false;
}
// 乘法
var total = parseInt(inputNum1.val()) / parseInt(inputNum2.val());
jQuery("#resultDiv")[0].innerHTML=
"<h2>计算相除的结果为:<strong style='color: chocolate;'>" + total + "</strong></h2>";
}
else if(type==5){
if(confirm("是否确认清空")) {
// 清空数据
inputNum1.val("");
inputNum2.val("");
jQuery("#resultDiv")[0].innerHTML="";
}
}
}
</script>
</head>
<body>
<div style="text-align: center;margin-top: 100px;">
<h1>计算器</h1><p></p>
数字1:<input id="num1" type="number"><p></p>
数字2:<input id="num2" type="number"><p></p>
<div>
<input type="button" value=" 相 加 " onclick="calc(1)">
<input type="button" value=" 相 减 " onclick="calc(2)">
<input type="button" value=" 相 乘 " onclick="calc(3)">
<input type="button" value=" 相 除 " onclick="calc(4)">
<input type="button" value=" 清 空 " onclick="calc(5)">
</div>
<div id="resultDiv" style="margin-top: 50px;">
</div>
</div>
</body>
</html>
最终呈现
注意这里只简单贴了相加功能的图片
总结
- 在写的过程中,遇到jquery无法调用innerHTML的问题,原生js写法为(以本文为例):
document.getElementById("resultDiv").innerHTML
,查询资料得知jquery没有innerHTML这个属性,要使用jQuery("#resultDiv")[0].innerHTML
语句,或者jQuery("#resultDiv").html();
语句。一开始看到之后不知道为什么要加[0]
,查后得知是要对jquery对象和js对象进行转换。 - jquery对象与dom对象的转换
只有jquery对象才能使用jquery定义的方法。dom对象和jquery对象是有区别的,普通的dom对象一般可以通过jQuery()
转换为jquery。
eg:jQuery(document.getElementById("resultDiv"))