我正在尝试创建一个简单、小型和基本的 javascript 框架,仅供学习之用。 但问题是我已经陷入了最基本的困境。
我正在尝试做这样的事情:
$('testdiv').testFunction();
我为此编写的代码:
var elementID;
var smallFramework = {
$:function(id) {
this.elementID = id;
},
testFunction:function() {
alert(this.elementID);
}
};
window.$ = smallFramework.$;
但作为返回我得到:
$('testdiv) is undefined
任何人都可以帮我解决这个小而简单的问题吗?
最佳答案
要获得您期望的行为,您需要 $
函数返回一个具有名为 testFunction
的方法的对象。
尝试:
var smallFramework = // an object for namespacing
{
$:function(id) // the core function - returns an object wrapping the id
{
return { // return an object literal
elementID: id, // holding the id passed in
testFunction: function() // and a simple method
{
alert(this.elementID);
}
};
}
};
当然还有many other ways实现您想要的行为。
关于javascript - 如何为 HTML 元素创建方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526526/