手动传递此onClick事件

时间:2012-09-19 21:30:08

标签: javascript jquery

如何从其他函数手动传递“this”值

的jQuery

$('#divName ul li a').click(function() {
    $(this).addClass('active');
});
$(window).scroll(function() {
    //for condition a
    //the value of this will a

    //for condition b
    //the value of this will be
});​

2 个答案:

答案 0 :(得分:1)

  var elem = '';
$('#divName ul li a').on('click',function(e){
     $(this).addClass('active');
     elem = $(this);
     alert(elem);
    e.preventDefault();
});


$(window).scroll(function(){

  // Use the elem variable here
    console.log('The Variable this is recently cliked element : '+ elem)   
 //for condition a
 //the value of this will a

//for condition b
 //the value of this will be
});​

检查此FIDDLE

答案 1 :(得分:0)

您是否尝试实施点击和滚动功能?将滚动处理程序放在单击处理程序中。

$("div").click(function(e) {
    var target = this;
    $(window).on("scroll.clickScroll", function(e) {
        // Use "target" as the reference to what was clicked on.
    }
}

请注意,当点击停止时,您必须删除处理程序:

$(window).off("scroll.clickScroll");

我在这里使用了事件名称间距来区分普通窗口滚动和专门的点击滚动。

相关问题