JS入门 用javascript 编写一个简单网页

JavaScript013

JS入门 用javascript 编写一个简单网页,第1张

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<script>

var oddSum = function(n,fn){

var sum = 0

fn = fn || function(n){

return n

}

for(var i=0i<ni++){

if((i+1)&1==1){

for(var j=0j<i+1j++){

if((j+1)&1==1)

sum+=fn(j+1)

}

}

}

return sum

}

var factorial = function(n){

return n>1 ? n*factorial(n-1) :1 

}

document.write('S=1+(1+3)+(1+3+5)+…+(1+3+5+…+19)'+oddSum(19))

document.write('<br>')

document.write('S=1!+ (1!+3! )+(1!+3!+5!)+…+(1!+3!+5!+…+19!)'+oddSum(19,function(n){ return factorial(n) }))

</script>

</head>

<body>

</body>

</html>

<!doctype html>    

<html>    

<head>    

<title>计算器</title>    

<meta charset="utf-8"/>    

<style type="text/css">    

.panel{    

   border:4px solid #ddd    

width:192px    

margin:100px auto    

}    

.panel p,.panel input{    

   font-family:"微软雅黑"    

font-size:20px    

margin:4px    

float:left    

}    

.panel p{    

   width:122px    

height:26px    

border:1px solid #ddd    

padding:6px    

overflow:hidden    

}    

.panel input{    

  width:40px    

height:40px    

border:1px solid #ddd    

}    

</style>    

<script type="text/javascript">    

//参数e用来接收传入的event对象    

function cal(e){    

//1.获取事件源,处理button的事件    

var obj=e.srcElement||e.target    

if(obj.nodeName !="INPUT"){    

  return    

}    

    

var value=obj.value    

var p=document.getElementById("screen")    

if(value=="C"){    

//2.如果是[C],则清空p    

p.innerText=""    

}else if(value=="="){    

//3.如果是[=],则运算    

var exp=p.innerText    

try{    

var result=eval("("+exp+")")    

//如果正确执行,将结果写入p    

p.innerText=result    

}catch(e){    

//发生错误,给予错误提示    

  p.innerText="Error."    

}    

}else{    

//4.如果是其它按钮,则将value追加到p中    

p.innerText+=value    

    

}    

}    

</script>    

</head>    

<body>    

<!--在最外层的div上注册单击事件,传入event对象,然后在函数中通过event判断出事件来源于哪一个button,    

    进而做出应有的处理。这样的好处是,避免在button上大量的注册事件。-->    

<div class="panel" onClick="cal(event)">    

<div>    

<p id="screen"></p>    

<input type="button" value="C">    

<div style="clear:both"></div>    

</div>    

<div>    

<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 style="clear:both"></div>    

</div>    

</body>    

</html>

这是我自学时候写的计算器