js中的寫出想jquery中的函式一樣呼叫

lonecloud發表於2017-09-03

1.IIFE:

  Immediately-Invoked function Expression 函式模組自呼叫

2.程式碼實現

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <div id="demo">的麼的事</div>
</head>
<body>
<script>
    (function () {
        document.write("好啊好啊");
    })();

    //定義$
    (window.$=function (args) {
        //定義val
        function val() {
            return getElem().innerHTML;
        }
        function getElem() {
            if(args!=null){
                if(args.indexOf("#")==0){
                    return document.getElementById(args.substring(args.indexOf("#")+1,args.length));
                }
            }
        }
        return {
            val:val
        }
    })();
    document.write($("#demo").val());
</script>
</body>
</html>

 

相關文章