我需要将this
发送到capIn()和capOut()函数中,以便我可以定位到正确的.slide子div。如何将this
传递给函数。这里指的是鼠标悬停的元素。
$(".slide").hover(function(){capIn();capOut();});
我需要将this
发送到capIn()和capOut()函数中,以便我可以定位到正确的.slide子div。如何将this
传递给函数。这里指的是鼠标悬停的元素。
$(".slide").hover(function(){capIn();capOut();});
从函数名 capIn
和 capOut
来看,它们是两种不同的行为。我认为你需要在 mouseenter
和 mouseleave
事件上分别执行两种不同的行为。而 hover
方法可以接收两个方法作为参数,一个用于处理 mouseenter
事件,另一个用于处理 mouseleave
事件。你可以尝试这样做:
$(".slide").hover(capIn, capOut);
你可以在 capIn
和 capOut
内使用 this
,它将指向你悬停的 .slide
元素。
function capIn(){
var $childrens = $(this).children();
}
function capOut(){
var $childrens = $(this).children();
}
mouseenter
和mouseleave
上同时调用两个函数。而您的代码在mouseenter
上调用capIn
,在mouseleave
上调用capOut
。现在,从原始发布者函数的名称来看,这可能是他们真正想要的,但我仍然想强调一下。 - T.J. CrowdercapIn
和capOut
,它们代表了两种不同的行为,这是有道理的。也许楼主不知道hover
函数对于mouseenter
和mouseleave
事件需要分别指定两个处理程序。 - ShankarSangoli$(".slide").hover(function(){
capIn.apply(this);
capOut.apply(this);
});
看这里:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
更新:
如果capIn
是为mouseenter
,capOut
是为mouseleave
,那么:
$(".slide").hover(function(){
capIn.apply(this);
}, function(){
capOut.apply(this);
});
ShankarSangoli
的解决方案更为简洁,但如果除了this
之外还需要传递其他参数,则可以使用capIn.apply(this, arguments)
。
...hover(function() { capIn.apply(this); }, function() { capOut.apply(this); })
,只需要 ...hover(capIn, capOut)
即可。在第一个例子中,根据 @amnotiam 的观点,应该是 capIn.apply(this, arguments);
。 - T.J. Crowder.hover(capIn.apply(this), capOut.apply(this))
不起作用。fn.apply(...)
是一个函数调用,因此您需要将其包装在匿名函数中。 - dgillandfunction capOut(jq) {
alert(jq.hasClass('slide'))
}
$(".slide").hover(function () {
capIn(this),
capOut($(this)) //to pass a jQuery object wrapping 'this'
});