麻烦帮看下,这段(jQuery)代码怎么能更好的重构一下呢?
谢谢啦,以前是写CSS比较多.
嘛,随便修改了一下,感觉会比你的稍微好一点,总的来说就是将重复功能函数化,尽量减少请求次数。
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()); });
})
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
6 回答1.1k 阅读