首页 > 自己写的js代码总感觉比较随意,不知道应该如何更好的组织~

自己写的js代码总感觉比较随意,不知道应该如何更好的组织~

麻烦帮看下,这段(jQuery)代码怎么能更好的重构一下呢?

谢谢啦,以前是写CSS比较多.

http://runjs.cn/code/1gk451id


  1. ajax请求相同地址应该只有一次
  2. 不要在each里append
  3. dd标签的click,应该用事件代理
  4. 相同渲染逻辑可以抽离出来单独做个函数
javascript$(function() {
    function main(data){
        var sel = $('select'),texture = $('.texture'),scene = $('.scene');
        texture.parent().on('click',"dd",function() {alert($(this).text());})
        var selHtml=data.map(function(val){
                return "<option data-value=" + val.val + ">" + val.title + "</option>";
        }).join("");
        sel.append(selHtml).on('change', function() {
            var val = parseInt($(this).find('option:selected').data('value'));
            $.each(data, function(i, n) {
                if(val > i) return true;
                handleDom(n.texture,texture);
                handleDom(n.scene,scene);
                return false;       
            })
        });
    }
    function handleDom(data,dom){
        var tmparr=[];
        $.each(data,function(i,n){tmparr.push("<dd>"+n+"</dd>");})
        if(dom){
            dom.find("dd").remove();
            dom.append(tmparr.join(""));
        }
    }
    $.getJSON('/uploads/rs/310/japcsu0l/data.json',main);
})

嘛,随便修改了一下,感觉会比你的稍微好一点,总的来说就是将重复功能函数化,尽量减少请求次数。
http://runjs.cn/code/5unw8k2y

var tpl = {
    render: function(d, s) {
        var multiRender = function(d, s) {
            return s.replace(/\{(.+?)\}/g, function(a,b){return d[b]});
        },
        singleRender = function(d, s) {
            return s.replace(/\{(.+?)\}/, d);
        };
        var r = typeof d != "object" ? singleRender : multiRender;
        return r.apply(this, [d, s]);
    },
    clear: function(o, t) {
        if(typeof o != "object") o = [o];
        else o = Object.keys(o).map(function(m){return o[m]})
        return o.forEach(function(n){ return $(t, n).remove() });
    },
    forEach: function(o, callback) {
        return Object.keys(o).forEach(function(v){callback(o[v],v)});
    }
};  
$(function() {
    function init(d) {
        var selectBox = $("select"), 
                showBox = { texture: $(".texture"), scene: $(".scene")};
        d.forEach(function(o) {
            selectBox.append( tpl.render(o, '<option data-value="{val}">{title}</option>') );
        })
        selectBox.on("change", function() {
            tpl.clear(showBox, "dd");
            var ds = d[ $(this).find("option:selected").data("value")/1 ] || {};
            tpl.forEach(showBox, function(o, i) {
                if( !ds[i] ) return false;
                ds[i].forEach(function(n){o.append(tpl.render(n, "<dd>{m}</dd>"))});
            })
        });
    }

    $.getJSON('/uploads/rs/310/japcsu0l/data.json', init);
    $(document).on("click", "dd", function() { alert( $(this).text() )});
})

即便是公子大大都未能統一你的編碼風格。。。真是太亂了!!!!!

statement 後面一定要加 semicolon,即便在大括號前(尤其是大括號前)。爲什麼?爲了迅速區分 statement block 和 object literal。

control keyword 和括號之間要有一個空格。爲什麼?爲了迅速與函數調用區分。

Member Expression 的中括號之間不要留空格。爲什麼?爲了與 Array Literal 區分。

小括號內部不要有空格,除非,所有的小括號內部都有空格。

大括號內永遠有空格,爲什麼?爲了迅速與小括號區分。

風格不重要,重要的是統一。但是這段代碼在公子大大修改後,依舊什麼風格都有。。。

var tpl = {
    render: function(d, s) {
        var r = typeof d != "object" ? singleRender : multiRender;

        function multiRender(d, s) {
            return s.replace(/\{(.+?)\}/g, function(a,b) { return d[b]; });
        }
        function singleRender(d, s) {
            return s.replace(/\{(.+?)\}/, d);
        }

        return r.apply(this, [d, s]);
    },
    clear: function(o, t) {
        if (typeof o != "object")
            o = [o];
        else
            o = Object.keys(o).map(function(m) { return o[m]; });

        return o.forEach(function(n) { return $(t, n).remove(); });
    },
    forEach: function(o, callback) {
        return Object.keys(o).forEach(function(v){  callback(o[v],v); });
    }
};  
$(function() {
    function init(d) {
        var selectBox = $("select"), 
            showBox = { texture: $(".texture"), scene: $(".scene") };

        d.forEach(function(o) {
            selectBox.append(tpl.render(o, '<option data-value="{val}">{title}</option>'));
        });

        selectBox.on("change", function() {
            var ds;

            tpl.clear(showBox, "dd");
            ds = d[$(this).find("option:selected").data("value")/1] || {};

            tpl.forEach(showBox, function(o, i) {
                if(!ds[i])
                    return false;

                ds[i].forEach(function(n){ o.append(tpl.render(n, "<dd>{m}</dd>")); });
            });
        });
    }

    $.getJSON('/uploads/rs/310/japcsu0l/data.json', init);
    $(document).on("click", "dd", function() { alert($(this).text()); });
})

楼上所说的你的代码风格太乱了这件事...
你可以把你的代码贴进http://www.jslint.com/ 里面滚一圈
最下面有一些选项可以设置的。

【热门文章】
【热门文章】