将$(this)传递给函数

Dre*_*ker 7 jquery function this

嘿伙计们,我正在尝试建立媒体播放列表,可以提升积分,播放视频并更改拇指悬停,视频结束和下一个/上一次点击的标题.所以我需要编写一些可以一起调用的函数.像这样:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );
Run Code Online (Sandbox Code Playgroud)

问题是$(this)不会从.hover传递到函数.我该怎么做呢?

谢谢您的帮助!

Phr*_*ogz 7

根据@ patrickdw的回答,jQuery将事件的回调范围设置为触发事件的DOM元素.例如,请参阅处理程序eventObject文档中的参数click().

当您想要创建一个jQuery插件时,我的原始答案(下面)很有用,这样您就可以在jQuery对象上调用自己的自定义方法,并this在执行期间设置jQuery对象.但是,这不是原始问题的正确和简单的答案.

// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
  function(){ $(this).showBox() },
  function(){ $(this).hideBox() }
);
Run Code Online (Sandbox Code Playgroud)

编辑:或者,如果(如建议的那样)您只想为~global jQuery方法命名空间添加一个名称:

$.fn.myBox = function(cmd){
  this.closest('.container').find('.box')[cmd]();
};

$('a').hover(
  function(){ $(this).myBox('show') },
  function(){ $(this).myBox('hide') }
);
Run Code Online (Sandbox Code Playgroud)

或者更一般地说:

$.fn.myBox = function(cmd){
  switch(cmd){
    case 'foo':
      ...
    break;
    case 'bar':
      ...
    break;
  }
  return this;
};
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅jQuery插件创作指南.


use*_*716 3

如果你这样做的话,就会this继续下去:

$('a').hover(showBox,hideBox);
Run Code Online (Sandbox Code Playgroud)

编辑:为了解决评论中的问题,这适用于您分配为事件处理程序的任何函数。它是匿名函数还是命名函数并不重要。

这:

$('a').click(function() { 
    alert( this.tagName ); 
});
Run Code Online (Sandbox Code Playgroud)

...是相同的:

function alertMe() {
    alert( this.tagName );
}

$('a').click( alertMe );
Run Code Online (Sandbox Code Playgroud)

...或这个:

function alertMe() {
    alert( this.tagName );
}

$('a').bind('click', alertMe );
Run Code Online (Sandbox Code Playgroud)