Javascript jQuery:临时禁用单击侦听器

Javascript jQuery:临时禁用单击侦听器,javascript,jquery,Javascript,Jquery,我有一个处理很多jQuery事件的应用程序,我需要一种区分简单点击和文本选择的方法 我想在检测到文本选择时禁用所有单击事件。这可能吗?我想过这样做: // User presses mouse button $(window).on('mousedown', function(){ // User moves mouse while pressing mouse button => selection this.one('mousemove', function(){

我有一个处理很多jQuery事件的应用程序,我需要一种区分简单点击和文本选择的方法

我想在检测到文本选择时禁用所有单击事件。这可能吗?我想过这样做:

// User presses mouse button
$(window).on('mousedown', function(){

    // User moves mouse while pressing mouse button => selection
    this.one('mousemove', function(){

        // Disable click listener temporarily
        $.fn.click = null;

    // User releases mouse button => end of selection
    }).on('mouseup', function(){

        // Stop mousemove event & restore click listener
        this.off('mousemove');
        $.fn.click = function(){};
    }); 
});
var flag = 0;
// User presses mouse button
$(window).on('mousedown', function(){
    if (flag == 0) {
        // do some if click event enabled
    }
    // User moves mouse while pressing mouse button => selection
    this.one('mousemove', function(){
        // Disable click listener temporarily
        // $.fn.click = null;
        flag=1;
        // User releases mouse button => end of selection
    }).on('mouseup', function(){
        // Stop mousemove event & restore click listener
        // this.off('mousemove');
        // $.fn.click = function(){};
        flag = 0;
    }); 
});

代码显然不起作用,但可以用来说明我的目标。有人知道实现这一点的好方法吗?

像设置标志这样简单的方法适用于您的示例

var flag = true;
...
if(flag === true)
{
   --Click listener enabled code here--
}
else
{
   --Click listener disabled code here--
}

您所要做的就是确定何时启用或禁用该标志。

只需使用该标志,如下所示:

// User presses mouse button
$(window).on('mousedown', function(){

    // User moves mouse while pressing mouse button => selection
    this.one('mousemove', function(){

        // Disable click listener temporarily
        $.fn.click = null;

    // User releases mouse button => end of selection
    }).on('mouseup', function(){

        // Stop mousemove event & restore click listener
        this.off('mousemove');
        $.fn.click = function(){};
    }); 
});
var flag = 0;
// User presses mouse button
$(window).on('mousedown', function(){
    if (flag == 0) {
        // do some if click event enabled
    }
    // User moves mouse while pressing mouse button => selection
    this.one('mousemove', function(){
        // Disable click listener temporarily
        // $.fn.click = null;
        flag=1;
        // User releases mouse button => end of selection
    }).on('mouseup', function(){
        // Stop mousemove event & restore click listener
        // this.off('mousemove');
        // $.fn.click = function(){};
        flag = 0;
    }); 
});

为什么要禁用单击侦听器?如果是这样,请使用
event.preventDefault()
,因为无论用户的意图如何,单击事件都会触发,这可能只是简单地选择文本。为什么首先要设置一个单击事件?我在文档中的不同元素上有许多单击事件处理程序,这就是为什么我想在用户选择文本时全局禁用它一次。这是可以撤消的,除非您跟踪所有的点击处理程序,并在需要时停止它们。