문제

My code is...

var timer;
var func = function () {
        $("body").append("1");
};

$(document).on('mousedown' , 'a' , function(e){
        timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
        clearTimeout(timer);
});

Everything working. But when I set this function to some link like <a href="http://google.com">text</a>

I need to set return false; (not redirect to the url or another onclick() functions)

Where return false; can I set in ? Or another solution ?

PS : And I will my link will work normally when click by normal clicking

Playground : http://jsbin.com/iwilop/1/edit


How can I listen for a click-and-hold in jQuery?

도움이 되었습니까?

해결책

You need to add a click handler and, if your func was called, prevent the default action of the click. Here I'm using timer as a flag:

var timer = 0;
var func = function () {
  $("body").append("1");
  timer = 0;
};

$(document).on('mousedown' , 'a' , function(e){
  timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
  if (timer) {
    clearTimeout(timer);
  }
}).on('click', 'a', function() {
  if (!timer) {
    return false;
  }
});

Updated JSBin

다른 팁

You need a click handler (you don't actually need to call return false unless there are other handlers that could also fire):

$(document).on('mousedown' , 'a' , function(e){
        timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
        clearTimeout(timer);
}).on('click', 'a', function(e) {
        return false;
});

Bear in mind that the above will affect all links on the page - you may need to qualify the a selector to be more specific (e.g. a.blah).

Edit: in light of your revised question, I have nothing to offer over and above T.J. Crowder's answer. The only thing I'd say is to watch out for global variables - you might want to wrap the whole thing in an immediately invoked function expression or similar.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top