Jquery事件发射错误。需要关闭?

时间:2012-05-19 14:45:46

标签: jquery closures this mouseenter mouseleave

我的功能是触发第二个mouseleave()事件而不是第一个事件,从而产生nth-child(1)&当我希望他们使用第一个将nth-child(2)属性设置为bottom:99px

mouseleave()事件时,bottom:94px的.css属性为$(document).ready(function(){ $('#rows').on('mouseenter', "div.row div:nth-child(1), div.row div:nth-child(2)",this , function() { $('img',this).stop().animate({"bottom":"0px"}, "fast"); }); $('div',this).off("mouseleave").on("mouseleave", function() { $('img',this).stop().animate({"bottom":"94px"}, "fast"); }); // need closure here? $('#rows').on('mouseenter', "div.row div:nth-child(3), div.row div:nth-child(4)",this , function() { $('img',this).stop().animate({"bottom":"0px"}, "fast"); }); $('div',this).off("mouseleave").on("mouseleave", function() { $('img',this).stop().animate({"bottom":"99px"}, "fast"); }); });

我相当肯定经过一些研究后我需要关闭我的(这个)语句,以便当我在第二轮参数中调用它时它在新范围内工作..?

{{1}}

2 个答案:

答案 0 :(得分:1)

我猜你想要这个:

$('#rows').on('mouseenter', "div.row div:nth-child(1), div.row div:nth-child(2)", this , function() {
    $('img', this).stop().animate({"bottom":"0px"}, "fast");

    // when placed inside, the value of this makes more sense?
    $('div', this).off("mouseleave").on("mouseleave", function() {
        $('img',this).stop().animate({"bottom":"94px"}, "fast");    
    }); 
});

在您撰写的此声明中,this的值可能为window,因此$('div', this)会定位页面上的所有div。

$('div', this).off("mouseleave").on("mouseleave", function() {
    $('img',this).stop().animate({"bottom":"94px"}, "fast");    
}); 

答案 1 :(得分:0)

我想也许你需要的是以下内容。这段代码未经测试,但它至少会给你一个要点:

$( document ).ready( function () {

  var rows, selector, listeners = {};

  rows = $( '#rows' );

  listeners.mouseenter = function () {

    $( 'img', this ).stop().animate( { "bottom" : "0px" }, "fast" );

  };


  listeners.mouseleave = function ( event ) {

    $( 'img', this ).stop().animate(

      { "bottom" : event.data.bottom + "px" }, "fast"

    );

  };


  selector = "div.row div:nth-child(1), div.row div:nth-child(2)";

  rows.on( 'mouseenter', selector, listeners.mouseenter );

  rows.off( 'mouseleave', selector );

  rows.on( 'mouseleave', selector, { bottom : 94 }, listeners.mouseleave );


  selector = "div.row div:nth-child(3), div.row div:nth-child(4)";

  rows.on( 'mouseenter', selector, listeners.mouseenter );

  rows.off( 'mouseleave', selector );

  rows.on( 'mouseleave', selector, { bottom : 99 }, listeners.mouseleave );

} );

在这种情况下,处理程序this内部将是与选择器匹配的元素(div的第n个孩子div.row)。

相关问题