Blogger Information
Blog 33
fans 0
comment 0
visits 20681
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js基础dom操作2018年9月12日
马聪 15558002279的博客
Original
457 people have browsed it
  1. 简易计算器:


  2. 实例

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>计算器</title>
    </head>
    <body>
    	<input type="test" name="num" placeholder="输入数字1" id = "num1"/>
    	<select id="oper">
    		<option value="">请选择运算符</option>
    		<option value="plus">+</option>
    		<option value="minus">-</option>
    		<option value="mul">x</option>
    		<option value="div">/</option>
    	</select>
    	<input type="test" name="num" placeholder="输入数字2" / >
    <br><br>
    <button type="button" id ="check" >计算</button><span style="color:red;padding-left:30px;" class="wrong"></span>
    <br><br><div>结果为:<span id="res"></span></div>
    
    <script type="text/javascript">
    	let button = document.getElementById('check');
    	button.onclick = function(){
    	let oper = document.getElementById('oper');
    	let res = document.getElementById('res');
    	let num= document.getElementsByName('num');
    		// alert(num[0].value + num[1].value);
    		// alert(oper);
    		if(num[0].value == "" || num[0].value.length==0 || num[1].value == "" || num[1].value.length==0){
    			show_wrong("数字1或数字2不能为空");
    		}else{
    			res.innerHTML = "";
    			num1 = parseInt(num[0].value)
    			num2 = parseInt(num[1].value)
    			switch(oper.value){
    			case "plus":
    				result = num1 +num2
    				str = num1 + '+' + num2 + '=' + result;
    				res.innerHTML = str;
    				break;
    			case "minus":
    				result = num1 - num2
    				str = num1 + '-' + num2 + '=' + result;
    				res.innerHTML = str;
    				break;
    			case "mul":
    				result = num1*num2
    				str = num1 + '乘' + num2 + '=' + result;
    				res.innerHTML = str;
    				break;
    			case "div":
    				if(num2==0){
    					show_wrong('除数不能为0')
    					break;
    				}
    				result = num1/num2
    				str = num1 + '除' + num2 + '=' + result;
    				res.innerHTML = str;
    				break;
    			default:
    				show_wrong("请选择操作符号");
    				break;
    		}
    		}
    		
    	}
    	function show_wrong(str){
    		document.getElementsByClassName('wrong')[0].innerHTML = str;
    	}
    </script>
    </body>
    </html>

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post