在javascript中将代码片段转换为方法
目前,为了将代码保存在一个对象中,我希望将单击事件的内容转换为一个方法,但不太确定这是如何实现的。当前代码如下所示: 当前JS在javascript中将代码片段转换为方法,javascript,jquery,Javascript,Jquery,目前,为了将代码保存在一个对象中,我希望将单击事件的内容转换为一个方法,但不太确定这是如何实现的。当前代码如下所示: 当前JS init: function(){ var _this = this, slides_li = _this.els.slides.children(), large = 260, small = 60; // Hover
init: function(){
var _this = this,
slides_li = _this.els.slides.children(),
large = 260,
small = 60;
// Hover
slides_li.on('mouseover', function(){
$(this).stop(true, true).animate({ opacity: 1 }, 300);
}).on('mouseout', function(){
$(this).stop(true, true).animate({ opacity: .8 }, 300)
});
// Click handlers
slides_li.on('click', function(){
//是否要将此代码移动到其自己的方法toggle_slides()
但我希望代码看起来像这样,但我知道我缺少一些关键的东西,而且这显然并不意味着点击事件:
JS
有人能就如何使这一点起作用提供一些建议吗?问题在于“this”的上下文相关值 首先,请注意原始代码的工作原理: 最初调用init()时,
此
引用父对象(gep)。但是在click事件处理程序中,这个
指的是clicked元素。因此,您仍然可以在单击处理程序中访问父级,您可以将“此的父级值”捕获到\u this
,以便以后可以使用它,并且一切正常
但是,当您将处理程序中的代码移动到一个单独的方法中时,会发生很多变化:
- 首先,小、大和其他变量不再在本地范围内,因此必须重新定义或作为参数导入
现在再次引用父元素,因为现在执行的方法不是事件处理程序,而是父元素上的方法。因此,在旧代码中引用此可以在新代码中使用此此
- 最后,在旧代码中,在事件处理程序中,
引用了被单击的元素。但是(见上文)在新方法中,这意味着一些不同的东西:“父”对象。因此,我们需要一个参数来捕获单击的元素-我已将其作为这个
参数传递,并且在旧代码中对el
的引用也会相应更改this
我把slider_li的内容移到了toggle_slides方法中,现在想调用它?init是对象bep的一部分,所以我调用bep.init();若要启动对象,那么是什么阻止您执行
bep.toggle\u slides()
?当我执行此操作时,会得到未捕获的引用错误:\u此未定义此处有一个小提琴:
$('.active', _this.els.slides).not(this).animate({
width: small
}, 300).removeClass('active');
// animate the clicked one
if ( !$(this).hasClass('active') ){
$(this).animate({
width: large
}, 300).addClass('active');
}
});
}
init: function(){
var _this = this,
slides_li = _this.els.slides.children(),
large = 260,
small = 60;
// Hover
slides_li.on('mouseover', function(){
$(this).stop(true, true).animate({ opacity: 1 }, 300);
}).on('mouseout', function(){
$(this).stop(true, true).animate({ opacity: .8 }, 300)
});
// Click handlers
slides_li.on('click', function(){
toggle_slides(); //pass in this?
});
},
toggle_slides: function(){ // add argument for this?
$('.active', _this.els.slides).not(this).animate({
width: small
}, 300).removeClass('active');
// animate the clicked one
if ( !$(this).hasClass('active') ){
$(this).animate({
width: large
}, 300).addClass('active');
}
}
...
// Click handlers
slides_li.on('click', function(){
// pass 'this' - the clicked element - as the el param; also small and large.
gep.toggle_slides(this, small, large);
});
},
toggle_slides: function(el, small, large){
// '_this' in old code in handler replaced with 'this';
// 'this' in handler code replaced with 'el' here
$('.active', this.els.slides).not(el).animate({
width: small
}, 300).removeClass('active');
// animate the clicked one
// 'this' in handler code replaced with 'el'here
if ( !$(el).hasClass('active') ){
$(el).animate({
width: large
}, 300).addClass('active');
}
}