2017-02-21 41 views
-1

我有点击和保持事件的动态元素JQuery的获得元素在SetTimer函数

var timeoutId = 0; 
    $(document).on('mousedown', '.createbtn', function(){ 
     timeoutId = setTimeout(showNewInfoCreateDlg, 1000); 
    }).on('mouseup mouseleave', '.createbtn', function() { 
     clearTimeout(timeoutId); 
    }); 

上的功能是“showNewInfoCreateDlg” 我需要知道什么是元素的id这是点击和持有

function showNewInfoCreateDlg(){ 
     alert($(this).attr('id')); 
    } 

功能警报“未定义”

这里是我的问题的jsfiddle:

JsFiddle

+0

http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback –

回答

1

显式绑定到功能:

var timeoutId = 0; 
$(document).on('mousedown', '.createbtn', function(){ 
    timeoutId = setTimeout(showNewInfoCreateDlg.bind(this), 1000); 
}).on('mouseup mouseleave', '.createbtn', function() { 
    clearTimeout(timeoutId); 
}); 

澄清:将bind()功能,那么,它的第一个参数的值绑定到变量this内部showNewInfoCreateDlg。这被称为显式绑定。

+0

太好了。谢谢 – user1137313

+0

不客气:) – AVAVT