首页 > 代码库 > JavaScript基础

JavaScript基础

函数返回值

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function show(){
            return 12;
        }
        var a=show();
        alert(a);
    </script>
</head>
<body>

</body>
</html>

加法器

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function add(a,b){
            return a+b;
        }

        alert(add(3,5));
    </script>
</head>
<body>

</body>
</html>

注意:return无值时,弹出undefined

求和  arguements可变参数组

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function sum()
        {
            var result=0;
            for(var i=0;i<arguments.length;i++){
                result+=arguments[i];
            }
            return result;
        }
        alert(sum(12,6,9))
    </script>
</head>
<body>

</body>
</html>

css(oDiv,‘width‘)获取样式

css(oDiv,‘width‘,‘200px‘)设置样式

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function css(){
            if(arguments.length==2)//获取 如果有2个参数
            {
                return arguments[0].style[arguments[1]];
            }
            else{//设置
                arguments[0].style[arguments[1]]=arguments[2];
            }
        }
        window.onload = function()
        {
            var oDiv=document.getElementById(div1);
            alert(css(oDiv,width));//css(oDiv,‘background‘,‘green‘);设置成绿色
} </script> </head> <body> <div id="div1" style="width:200px;height:200px;background: red"></div> </body> </html>

 

技术分享

简化,给函数取名

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function css(obj,name,value)
        {alert(obj==arguments[0]);

            if(arguments.length==2)//获取 如果有2个参数
            {
                return obj.style[name];
            }
            else{//设置
                obj.style[name=value;
            }
        }
        window.onload = function()
        {
            var oDiv=document.getElementById(div1);
            //alert(css(oDiv,‘width‘));
            css(oDiv,background,green)
        }
    </script>
</head>
<body>
<div id="div1" style="width:200px;height:200px;background: red"></div>
</body>
</html>

 

JavaScript基础