编写一个JavaScript js程序

JavaScript08

编写一个JavaScript js程序,第1张

按照你的要求编写的输出日期属于该年的第几天的Javascript程序如下

<html>

<head>

<script type=text/javascript> 

function check(){

 var year=parseInt(document.getElementById("year").value)

 var month=parseInt(document.getElementById("month").value)

 var day=parseInt(document.getElementById("day").value)

 if(year<2000 || year>2018){

  alert("输入年份要求在2000到2018之间")

  var t = document.getElementById("year")

      t.focus()

      return false

 }

 var days=0

 for(var i=1i<monthi++){

  switch(i){

   case 1:

   case 3:

   case 5:

   case 7:

   case 8:

   case 10:

   case 12:days=days+31break

   case 4:

   case 6:

   case 9:

   case 11:days=days+30break

   case 2:

    if(year%4==0&&year%100!=0||year%400==0)

     days=days+29

    else

     days=days+28

    break

  }

 }

 days=days+day

 document.getElementById("result").innerHTML="该日期是"+year+"年的第"+days+"天"

}

</script>

</head>

<body>

 年份<input type="text" name="year" id="year" value=""><br>

 月份<input type="text" name="month" id="month" value=""><br>

 日期<input type="text" name="day" id="day" value=""><br>

 <input type="button" value="确定" onclick="check()"><br>

 <div id="result"></div>

</body>

</html>

在任何IDE和编辑器中都可以编写JS前端程序,而我们只需要注意注意JS语言的规范就行了。

目前在HTML文件中,运性JS有两种方式,一种是内嵌代码;另一种是编写单独的JS文件,然后引用。

第一种:内嵌代码

就是在<script type="text/javascript"></script>中直接编写代码,例如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>首页/title>

    <script type="text/javascript">

        alert("我是运性结果")

    </script>

</head>

<body>

</body>

</html>

第二种:外部引用

在<script>标签上添加一个src属性指向文件地址。

例如我们在user.js文件中写上:

alert("我是运性结果")

然后在HTML中引用:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>首页</title>

    <script type="text/javascript" src="user.js">

</head>

<body>

</body>

</html>

上面两种的运性结果一样,都是在浏览器中弹出一个提示框

编写js程序的位置不包括嵌入在标签中。可以在网页文件的script标签进行嵌入,将脚本程序代码放置在一个单独的文件中,在网页中引用这个脚本程序文件编写JavaScript的脚本代码。