function _(e) {
if (typeof e == 'string') {
if (e.charAt(0) == '#') {
return document.getElementById(e.slice(1));
} else if (e.charAt(0) == '.') {
var c = document.getElementsByClassName(e.slice(1));
return (c.length==1)?c[0]:c;
} else {
var t = document.getElementsByTagName(e);
return (t.length==1)?t[0]:t;
}
} else {
console.log('Error. Not a valid string in _.');
}
}
_.prototype.hide = function() {
//testing
console.log(this)
}
該功能工作正常,但是當我嘗試添加方法隱藏並嘗試並調用它像_('#menu').hide();
時,它會拋出錯誤:TypeError: Object #<HTMLDivElement> has no method 'hide'
我誤解了什麼?爲什麼這個原型失敗?
是的,我沒有谷歌這個問題,我只是不明白。一個提示將不勝感激。
它在我看來像你試圖調用隱藏的返回值功能。我期望:var x = new _('#menu'); x.hide();去工作,但我不認爲這就是你想要的。也許你應該返回一個對象來調用隱藏功能。 – jjrdk 2012-02-10 09:52:58
必須在'hide()'中設置'return' – diEcho 2012-02-10 09:53:41