We in the daily transport code, often because the code is too chaotic and lead to a long time after the code is difficult to handle, even the old drivers have to play a dozen points of spirit, such as the following code (everyone across the line) :

$(document).ready(function(){
            if(! getCookie("showNotice")) {
                setCookie("showNotice"."1".1);
                document.querySelector(".shadowBg").style.display = "flex";
                document.querySelector(".new_year_notice span").addEventListener('click'.function () {
                    document.querySelector(".shadowBg").style.display = "none";
                });
            }
             var newBanner = mcBanner();
            newBanner.switchBanner('mcBannerBox'.'.mcBannerChild'.'.bannerDotBox'.5000);
            
            sliderBox({
                id: document.getElementById('dynamic-list'),
                direction: 'top'.intervalTime: 5000
            });
            sliderBox({
                id: document.getElementById('honor-box'),
                direction: 'left'.intervalTime: 6000.clickLeft: document.getElementById('honor-box-left'),
                clickRight: document.getElementById('honor-box-right')});let _countTo = document.querySelectorAll('.countTo'),
                _countTo_len = _countTo.length;
            for (let i=0; i < _countTo_len; i++) {
                countTo({
                    id: _countTo[i],
                });
            }
            slideWord(document.getElementById('slideHonor'));
            $.ajax({
                url:'/payusercount'.type:'GET'.dataType:'json'.success:function(data){
                    var _box = document.getElementById("box");
                    for (var i = 0; i < data.length; i++) {
                        _box.innerHTML += "<li><span>"+  data[i].mobile  +" Purchased"+  data[i].month  +"Months < / span > < / li >"
                    }
                    sliderBox({
                        id: document.getElementById('box'),
                        direction: 'top'.intervalTime: 3000
                    });
                }
            })
            $.ajax({
                url:'/platform'.type:'GET'.dataType:'json'.success:function(data){
                    document.getElementById("statistics1").dataset.count = data[0].number;
                    document.getElementById("statistics2").dataset.count = data[1].number;
                    document.getElementById("statistics3").dataset.count = data[2].number;
                    document.getElementById("statistics4").dataset.count = data[3].number;
                    let _countTo = document.querySelectorAll('.countTo'),
                    _countTo_len = _countTo.length;
                    for (let i=0; i < _countTo_len; i++) {
                        countTo({
                            id: _countTo[i],
                        });
                    }
                }
            })
        })
        $.ajax({
            url:'/news/category'.type:'GET'.dataType:'json'.success:function(data){

                var artStr = ' ';
                var categoryCount = 0;
                for (var item in data.categories)
                {
                    if(categoryCount > 2) break;
                    categoryCount++;
                    var articleCount=0;
                    var temStr = ' '
                    var strHead = ' ';
                    var strBottom = ' ';
                    var str = ' ';
                    strHead += '<li><div class="news-img"><img src="'+data.categories[item].path+'" alt=""/></div><div class="news-url">';
                    strBottom += '</div><p class="more"><a href="/news/category/'+(data.categories[item].id)+'>

'
newitem = data.categories[item].id; for (var articleItem in data.articleLists[newitem]) { articleCount++; if(articleCount == 5) break; str += "<p><a href='/news/article/"+data.articleLists[newitem][articleItem].id+"' >"; str += data.articleLists[newitem][articleItem].name str += "</a></p>"; }; temStr = strHead + str + strBottom; artStr += temStr }; $('.e-artical').append(artStr); }})Copy the code

This code may seem long, but it’s just the tip of the iceberg. If all such codes are in a project, it can basically be said to be obsolete, because in the daily iteration of the project, we can only keep piling up the code, constantly making the whole project more chaotic and bloated.

On the other hand, a lot of people use frameworks to develop projects these days, but remember, as long as you’re confident and casual, you can still write messy code, trust me, really!

The code is presented below, with explanations interspersed directly into the corresponding comments of the code for easy comprehension

$(document).ready(function(){
            var thisPageThings = (function() {/* Outside of this can be written functions that can be used multiple times in the methods of the objects below, which can also be considered private functions */return{/* Every time you add relevant code, please create a new method in the object, write the new code in the new code, unified management of all the fragmented code, cut the chaotic code into pieces */ addBan:function() {$('.addBan').click(function () {
                            var id = $(this).data('id');
                            $.ajax({
                                url:'/addclick'.type:'GET',
                                data:{'id':id},
                                success:function(res){ console.log(res); }})}); }, onceModal:function () {
                        var res = document.cookie.indexOf("first_visit");
                        if(res == -1){ var exp =new Date(); console.log(exp.getTime()); exp.setTime(exp.getTime() + (21 - exp.getHours()) * 60 * 60 * 1000); // One hour ahead of time document.cookie ="first_visit=1; expires="+ exp.toGMTString(); // Test document.querySelector(".shadowBg").style.display = "flex";
                            document.querySelector(".new_year_notice span").addEventListener('click'.function () {
                                document.querySelector(".shadowBg").style.display = "none";
                            });
                        }
                    },
                    mcBannerBox: function() {$('.mcBannerChild').length > 1 && (function () {
                            var newBanner = mcBanner();
                            newBanner.switchBanner('mcBannerBox'.'.mcBannerChild'.'.bannerDotBox', 5000); } ()); }, dynamicList:function() {$('#dynamic-list').children().length && sliderBox({
                            id: document.getElementById('dynamic-list'),
                            direction: 'top',
                            intervalTime: 5000
                        });
                    },
                    honorBox: function() {$('#honor-box').children().length && sliderBox({
                            id: document.getElementById('honor-box'),
                            direction: 'left',
                            intervalTime: 6000,
                            clickLeft: document.getElementById('honor-box-left'),
                            clickRight: document.getElementById('honor-box-right')}); }, slideHonor:function () {
                        slideWord(document.getElementById('slideHonor'));
                    },
                    payusercountAjax: function () {
                        var _this = this;
                        $.ajax({
                            url:'/payusercount'.type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('payusercountAjax', data); }}); }, platformAjax:function () {
                        var _this = this;
                        $.ajax({
                            url:'/platform'.type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('platformAjax', data);
                            }
                        })
                    },
                    categoryAjax: function () {
                        var _this = this;
                        $.ajax({
                            url:'/news/category'.type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('categoryAjax', data);
                            }
                        })
                    },
                    //此处放置所有的订阅
                    allSubscription: function () {
                        this.event.subscribe('payusercountAjax'.function (data) {
                            var _box = document.getElementById("box");
                            for (var i = 0; i < data.length; i++) {
                                _box.innerHTML += "<li><span>"+  data[i].mobile  +" Purchased"+  data[i].month  +"Months < / span > < / li >"
                            }
                            sliderBox({
                                id: document.getElementById('box'),
                                direction: 'top',
                                intervalTime: 3000
                            });
                        });
                        this.event.subscribe('platformAjax'.function (data) {
                            var _countTo = document.querySelectorAll('.countTo'),
                                _countTo_len = _countTo.length;
                            for (var i=0; i < _countTo_len; i++) {
                                document.getElementById("statistics"+ i).dataset.count = data[i].number; countTo({ id: _countTo[i] }); }}); this.event.subscribe('categoryAjax'.function (data) {
                            var artStr = ' ';
                            var categoryCount = 0;
                            for (var item in data.categories)
                            {
                                if(categoryCount > 2) break;
                                categoryCount++;
                                var articleCount=0;
                                var temStr = ' ';
                                var strHead = ' ';
                                var strBottom = ' ';
                                var str = ' ';
                                strHead += '<li><div class="news-img"><img src="'+data.categories[item].path+'" alt=""/></div><div class="news-url">';
                                strBottom += '</div><p class="more"><a href="/news/category/'+(data.categories[item].id)+'>

'
; newitem = data.categories[item].id; for (var articleItem in data.articleLists[newitem]) { articleCount++; if(articleCount == 5) break; str += "<p><a href='/news/article/"+data.articleLists[newitem][articleItem].id+"' >"; str += data.articleLists[newitem][articleItem].name; str += "</a></p>"; } temStr = strHead + str + strBottom; artStr += temStr } $('.e-artical').append(artStr); }); }}; } ()); // This is the configuration for the self-executing code above. If you need to organize code such as some design patterns (functionVar event = {clientList: [], subscribe:function (key, fn) { if(! this.clientList[key]) { this.clientList[key] =[]; } this.clientList[key].push(fn); }, publish:function () { var key = Array.prototype.shift.call( arguments ), fns = this.clientList[ key ]; if ( !fns || fns.length === 0 ) { return false; } for( var i = 0, fn; fn = fns[ i++ ]; ) { fn.apply( this, arguments); }}}; // Integrate the publish-and-subscribe method into the object to be usedfunction (obj) { obj[ 'event'] = event; }; installEvent( thisPageThings ); // Execute all code fragments uniformlyfor (var thing in thisPageThings) { typeof thisPageThings[thing] === 'function' && thisPageThings[thing](); } }()); }); Copy the code

Structuring your code from the start can be beneficial, both for readability and for future extensions. For example, self-executing configurations can be organized into a common file that can be used anywhere. Even if only one place is used, this structure makes it easy to be DRY — Don’t repeat Yourself!