jQuery - Prevent activation on first click

2019-06-07 06:53发布

I have an issue that requires an albeit strange workaround. Essentially, I have a menu on a tablet that needs to ignore the user clicking/selecting the link the first time, but once selected the second time, it then executes the link.

So say we have a link here that goes to Google: Google.com

How can I stop the window from loading the link until it's clicked a second time? This is so multiple menu items can be clicked if they have children to show the submenus.

I've looked around and all I've found is event.stopImmediatePropagation();

But this ignores all click events entirely, which is not what I need.

Is it possible to do this? There should be a way to detect click count, surely?

5条回答
孤傲高冷的网名
2楼-- · 2019-06-07 07:25

I would make a globally accessible counter variable and then make an if statement around what you want to run inside that click function so that it only executes when you want. Ex:

var counter = 0;

example.addEventListener( "click", function() {
    if ( counter > 0 ) {
        //do action
    }
    counter++;
}

Hope that helps!

查看更多
smile是对你的礼貌
3楼-- · 2019-06-07 07:25

One way to achieve the requirement is to use data attributes.

When user clicks the link, check if the data attribute (let's say 'data-clicked-once') exists on that link element. If not, setup this attribute to 'true'. If the attribute exists, execute the code for showing the menu.

$('a#menu').on('click', function(){
    var $a = $(this);
    if($a.attr('data-clicked-once') === 'true'){
        //show the menu
    }else{
        $a.attr('data-clicked-once','true');
    }
});

Note that when you get attributes from .attr() it always returns string

查看更多
地球回转人心会变
4楼-- · 2019-06-07 07:29

you could try adding a variable to detect if it has been clicked yet:

var hasBeenClicked = false;

then when it is clicked:

if (hasBeenClicked) {
    // logic to follow the link
} else {
    hasBeenClicked = true;
}
查看更多
欢心
5楼-- · 2019-06-07 07:30

You can check for a class say, .clicked, if found follow the link, if not found -- that must be the first click -- do not follow the link, add the class clicked:

$('.a').on('click', function(e) {
    if( !$(this).is('.clicked') ) {
        e.preventDefault();
        $(this).addClass('clicked');
    }
});

DEMO

查看更多
迷人小祖宗
6楼-- · 2019-06-07 07:34

You can use something similar to this :

var clickBtn = false;

$('#link').click(function(e){
    if(clickBtn == false){
        e.preventDefault();
    }
    clickBtn = true;
});

Fiddle

查看更多
登录 后发表回答