无法引用我的 JQuery 原型类上的方法
Cannot reference methods on my JQuery prototype class
我像这样定义content_item
元素的行为:
$.fn.makeContentItem = function() {
$(this).selectItem = function() {
$(".content_item").removeClass("selected");
$(this).addClass("selected");
console.log($(this).css('width'));
}
$(this).click(function(event) {
console.log($(this));
$(this).selectItem();
});
}
然后,我将makeContentItem应用于:
$(".content_item").makeContentItem();
单击 content_item
元素会生成此错误:
Uncaught TypeError: Object [object Object] has no method 'selectItem'
您将该方法添加到 jQuery 集合,然后丢弃该 jQuery 集合。相反,您应该将其添加到元素数据结构中并从中引用它。
$.fn.makeContentItem = function() {
this.data("selectItem",function() {
$(".content_item").removeClass("selected");
$(this).addClass("selected");
console.log($(this).css('width'));
});
this.click(function(event) {
console.log($(this));
$(this).data("selectItem").call(this);
});
}
或者更好的是,让它成为一个私人功能。
$.fn.makeContentItem = function() {
var selectItem = function() {
$(".content_item").removeClass("selected");
$(this).addClass("selected");
console.log($(this).css('width'));
};
this.click(function(event) {
console.log($(this));
selectItem.call(this);
});
// and to make it a complete plugin, return this.
return this;
}
相关文章:
- 使用“;这个“;JavaScript原型方法中的关键字
- 引用类变量中的原型方法
- 如何从对象的原型方法访问JavaScript对象属性
- 什么意思是“;向原型添加方法”;
- 如何将原型用于自定义方法和对象操作
- 如何从构造函数中调用js原型方法
- Javascript不调用原型方法
- jQuery如何在原型中调用方法
- 为什么不't loadash/aunderline将util方法放在数组原型上
- 有没有任何情况下,一个方法不应该是原型方法
- 调用影子原型方法的更简单/更好的方法
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- 用于数组原型的JavaScript独特方法
- 当对象从服务器发送到客户端时,JS原型方法消失了
- 构造 JavaScript Array 原型方法
- 无法将方法原型添加到 JavaScript 对象
- Javascript对象方法原型
- 将方法原型化为子对象
- 继承方法(原型)和静态方法(表达式)的区别是什么?
- javascript中的闭包方法原型