好程序员HTML5大前端分享之函数篇

好程序员HTML5大前端分享之函数篇,将代码编写在函数中,就可以避免在非必要情况下调用该代码,也就是说我们可以让一段代码在特定情况下再去执行。

function 关键字:该关键字表示要声明一个函数。

如何执行函数()

function m1(){

    //xxxxxxxxxxxxx

}

for(var i=0;i<10;i++){
    m1();
}

刚才提到,函数的意义就是在特定情况下运行函数,那么什么是特定的情况那?

JavaScript是事件驱动的语言!

事件:用户的行为。

onclick、ondblclick、onfocus、onblur

例如点击按钮;弹出123;

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <button type="button"onclick = btn()>弹框</button>
    </body>
    <script type="text/javascript">
        function btn (){
            alert(123);
        }
    </script>
</html>

函数的参数

function m1(v1, v2, v3...){
    //xxxxxxxxxxxxx
}

return关键字
带返回值的函数

案例:

年月日分别为自定义函数的参数,判断是否为正确的日期

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script>
        function date(year,month,day){
            switch(month){
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:if(day<0||day>31){
                    return '错误的日期';
                }
                break;
                case 2:if(year % 4 == 0 || year% 400 == 0 && year % 100 != 0){
                    if(day>29||day<0){
                        return '错误的日期';
                    }
                }else{
                    if(day>28||day<0){
                        return '错误的日期';
                    }
                }
                break;
                default:if(day>30||day<0){
                    return '错误的日期';
                }
            }
            if(year>2050||year<0){
                return '错误的年份';
            }else if(month>12||month<0){
                return '错误的月份';
            }else{
                return '正确的日期'
            }
        };
        alert(date(2000,2,30))
        </script>
    </head>
    <body>
    </body>
</html>

评论

暂无评论