eg:判断2013年2月份是28还是29天
<script>
var year=2013;
var month=0;
if((year%4==0&&year%100!=0)||year%400==0){
month=29;
}else{
month=28;
}
alert(month);
</script>
image.png
3.1判断用户是否输入了用户名和密码
<body>
<form name="form1" method="post" action="">
<table width="226" border="1" cellpadding="0" cellspacing="0" bordercolor="#FFFFFF" bordercolordark="#CCCCCC" bordercolorlight="#FFFFFF">
<tr>
<td height="30" colspan="2" bgcolor="#eeeeee">#用户登录#</td>
</tr>
<tr>
<td width="89" height="30">用户名: </td>
<td width="132"><input name="user" type="text" id="user" /></td>
</tr>
<tr>
<td height="30">密 码:</td>
<td><input name="pwd" type="text" id="pwd" /></td>
</tr>
<tr>
<td height="30" colspan="2" align="center"><input name="Button" type="button" class="btn_grey" value="登录" onclick="return check()" />
<input name="Submit2" type="reset" class="btn_grey" value="重置" /></td>
</tr>
</table>
</form>
<script language="javascript">
function check(){
var name=form1.user.value;
var pwd=form1.pwd.value; //获取信息
if(name==""){
alert("用户名不能为空!");
form1.user.focus(); //用户名文本框获取焦点
return;
}else if(pwd==""){
alert("密码不能为空!");
form1.pwd.focus();
return;
}else{
form1.submit(); //提交表单
}
}
</script>
</body>
image.png
3.2定义一个变量获取当前时间,然后再用getHours()方法获取系统当前小时值,最后用else if在不同时间段输出不同问候语
<script language="javascript">
var nowtime=new Date();
var hour=nowtime.getHours();
if((hour>5)&&(hour<=7)) alert("早上好");
else if((hour>7)&&(hour<=11)) alert("上午好");
else if((hour>11)&&(hour<=13)) alert("中午好");
else if((hour>13)&&(hour<=17)) alert("下午好");
else if((hour>17)&&(hour<=21)) alert("晚上好");
else alert("该睡觉了");
</script>
image.png
3.3用switch判断今天是星期几
<script language="javascript">
var nowtime=new Date();
var day=nowtime.getDay();
var week;
switch(week){
case 1:
week="周一";
break;
case 2:
week="周二";
break;
case 3:
week="周三";
break;
case 4:
week="周四";
break;
case 5:
week="周五";
break;
case 6:
week="周六";
break;
default:
week="周日";
break;
}
document.write("今天是:"+week);
</script>
image.png
3.4通过while循环语句实现在页面中列举出累加和不大于10的所有自然数
<script language="javascript">
var i=1;
var sum=i;
document.write("累加和不大于10的所有自然数为:"+"<br>");
while(sum<=10){
sum+=i;
document.write(i+"<br>");
i++;
}
</script>
image.png
3.5计算100以内所有奇数的和
<script>
var sum=0;
for(i=1;i<100;i+=2){
sum+=i;
}
alert("100以内所有奇数的和为:"+sum);
</script>
image.png
3.6用continue计算所有偶数的和
<script>
var sum=0;
for(i=0;i<100;i++){
if(i%2==0){
sum+=i;
}else{
continue;
}
}
alert("100以内所有偶数和为:"+sum);
</script>
image.png
3.7用for语句制作一个乘法口诀表
<script>
for(i=1;i<=9;i++){
document.write("<table border=1 cellspacing=0 cellpadding=0 bordercolor=#cccccc>");
document.write("<tr>");
for(j=1;j<=i;j++){
document.write("<td width=60 align=center>");
document.write(j+"*"+i+"="+j*i);
document.write("</td>");
}
document.write("</tr>");
document.write("</table>");
}
</script>
image.png
网友评论