js计算器

                                                                                                                                                                                                首页http://blog.csdn.net/qq_15766257

首先练习用js创建 html元素;
createElement
appendChild
getElementsByTagName
先设计好按键有5排8列,每个用div包住;
创建方式可以采用双循环;
for(){
for(){}
}
全局函数eval
可以把字符串当作代码执行

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>hello</title>
   <script> //加载界面的模块,包括事件也可以一起加载 function load() { var sign = new Array( new Array("=", "(", ")", "退格", "清除", "存取", "取存" ), new Array("7","8", "9", "+", "%","空","空" ), new Array("4", "5","6", "-", "sqrt", "ln", "exp"), new Array("1", "2", "3","*", "sin", "cos", "tan" ), new Array("0", ".", "+/-", "/","asin", "acos", "atan") ); for (var i = 0; i < 5; i++) { var node = document.createElement("div"); document.body.appendChild(node); node.style.height = "21px"; node.style.width = "600px"; for (var j = 0; j < 7; j++) { var node1 = document.createElement("input"); document.getElementsByTagName("div")[i + 1].appendChild(node1); // node1.style.backgroundColor = "#FFCC80"; node1.style.height = "21px"; node1.style.width = "53px"; node1.setAttribute("type", "button"); node1.setAttribute("value", sign[i][j]); var c = node1.value; switch (c) { case "退格": node1.onclick = function () { var e = document.getElementsByTagName("input")[0].value; document.getElementsByTagName("input")[0].value = e.slice(0, e.length - 1); }; break; case "清除": node1.onclick = function () { document.getElementsByTagName("input")[0].value = ""; }; break; case "存取": break; case "取存": break; case"空": break; case "=": node1.onclick = function () { var h = document.getElementsByTagName("input")[0].value; h = h.replace(/sin/g, "Math.sin"); h = h.replace(/cos/g, "Math.cos"); h = h.replace(/tan/g, "Math.tan"); h = h.replace(/asin/g, "Math.asin"); h = h.replace(/aMath.sin/g, "Math.asin"); h = h.replace(/acos/g, "Math.acos"); h = h.replace(/aMath.cos/g, "Math.acos"); h = h.replace(/atan/g, "Math.atan"); h = h.replace(/aMath.tan/g, "Math.atan"); h = h.replace(/exp/g, "Math.exp"); h = h.replace(/ln/g, "Math.log"); h = h.replace(/sqrt/g, "Math.sqrt"); try { h = eval(h); }//重要计算函数 catch (exception) { window.alert(exception); } document.getElementsByTagName("input")[0].value = h; } break; default: node1.onclick = function(num) { return function () { var d = document.getElementsByTagName("input")[0].value + num; //字符串加法 document.getElementsByTagName("input")[0].value = d; //因为没有指针,所以值传递必须再传回来 ,也体会到通过结点的 js调用方法,可以更加灵活。 }; }(c); } } } } i = null; j = null; </script>
</head>
<body onload="load()">
  <div id="div1">
      <input value=""/>
  </div>
</body>
</html>

图:

你可能感兴趣的:(js计算器)