2
var Stuff = (function() {
return {
getId: function (id) {
return document.getElementById(id);
},
attr: function (ele, attr, newVal) {
var newVal = newVal || null;
if (newVal) {
ele.setAttribute(attr, newVal);
} else {
var attrs = ele.attributes,
attrslen = attrs.length,
result = ele.getAttribute(attr) || ele[attr] || null;
if (!result) {
for (var i = 0; i < attrslen; i++)
if (attr[i].nodeName === attr) result = attr[i].nodeValue;
}
return result;
}
}
}
})();
有了這個網站:轉換一個JavaScript庫鏈方法
<div id="foo" data-stuff="XYZ">Test Div</div>
當前實現:
(function ($) {
console.log(
$.attr($.getId('foo'), 'data-stuff') // XYZ
);
})(Stuff);
如何改寫上面我的圖書館,使其鏈像下面?
(function ($) {
console.log(
$.getId('foo').attr('data-stuff') // XYZ
);
})(Stuff);
不錯,這是一個相對無痛的修復代碼更乾淨 – tester 2010-12-13 23:04:51