Javascript 向$的原型添加函数(此)
我正在扩展,我已经达到了一个特定的点,通过Javascript 向$的原型添加函数(此),javascript,jquery,carousel,Javascript,Jquery,Carousel,我正在扩展,我已经达到了一个特定的点,通过\uuuuu prototype\uuuu定义新函数。我缩小了代码以演示基本部分: (function($) { var aux = { navigate : function(){ //... }, } methods = { init : function( options ) { return this.each(functi
\uuuuu prototype\uuuu
定义新函数。我缩小了代码以演示基本部分:
(function($) {
var aux = {
navigate : function(){
//...
},
}
methods = {
init : function( options ) {
return this.each(function() {
var $el = $(this);
//THIS IS THE SLIPPERY LINE:
$el.__proto__.scrollOneLeft = function() {
aux.navigate( -1, $el, $wrapper, $.extend(settings, {sliderSpeed: 10, sliderEasing: ''}), cache );
};
});
}
}
$.fn.contentcarousel = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.contentcarousel' );
}
};
})(jQuery);
这在现代浏览器上是可行的,但问题是,$el.\uuuuu proto\uuuuu
在IE9和IE10中还不起作用。我不是jQuery忍者,所以我想这不是合适的解决方案
所以我的问题是,在这种情况下,如何正确定义新方法?是的,这不是正确的方法。jQuery具有很强的扩展能力,并且已经以跨浏览器的方式介绍了这种情况
您可以通过以下方式在jQuery数组对象上定义新函数:
jQuery.fn.asdfize = function () {
this.html('asdf');
return this; // for chainability
}
您可以使用$('div').asdfize()
将所有div的innerHTML替换为asdf
这基本上就是您需要的,因为$(This)
将jQuery数组对象(jQuery.fn
)作为它的原型
老jquerywiki有一篇很好的文章介绍了这一点
编辑:
您已经在代码中使用$.fn.contentcarousel
完成了此操作。另一个案例有什么不同
EDIT2:
在代码的这一部分中:
return this.each(function() {
var $el = $(this);
$el.__proto__.scrollOneLeft = function() { ... };
});
您可以在每次迭代中覆盖scrollOneLeft
函数。这可能不是你想要的
您可能只想定义一次函数,但在函数中使用
this
,因为它将是您调用它的jQuery对象。嘿,SoonDead,谢谢您的解决方案!到目前为止,它正在发挥作用。我不会说我理解它,所以现在我要读关于$。fn
基本上它是:)好的,那么$el
应该被这个替换吗?正如我在《插件创作指南》中所读到的,它被不必要地包装了(如$this
),对吧?这是最重要的。因此,$(这个)
在scrollOneLeft
函数yes中是不必要的,因为它已经是jQuery对象了。但是请记住,许多jQuery函数(如.each()
)对原始DOM元素调用它们的回调函数。不要混淆这两种情况。:)小心,在循环中覆盖函数!