Jquery - 阻止<a> on first click, allow default action on second click

时间:2015-10-17 21:16:07

标签: javascript jquery html

How would I prevent the default action of an <a> on the first click (in order so that a tooltip is shown), then on the second click have the user directed to the value of the href attribute set on the element?

HTML

<a id="second" href="https://www.test.com/"  title="" class="customtooltip c_tool2"   data-original-title="data del toolltip numero 2">tooltip</a> 

Jquery

var t = $('.c_tool2'), b = $('a[href^="http');

b.click(function(e){
  if(t.length > 0){
    e.preventDefault();
    t.tooltip('show');
  } else {
    // on second click direct user to value of href 
  }
});

2 个答案:

答案 0 :(得分:2)

假设会有多个元素,使用公共计数器将无法正常工作。您可以使用data-*属性

在单个元素上使用计数器

此外,选择锚点的选择器不正确。

var t = $('.c_tool2'),
    b = $('a[href^="http"]'); // <-- Added "] to make it correct

b.click(function (e) {
    // Get the counter for clicked element
    var clickCount = parseInt($(this).data('count'), 10) || 0;

    // If counter is zero i.e. for the first click
    if (!clickCount) {
        // Update the value of the counter
        $(this).data('count', ++clickCount);
        t.tooltip('show');

        // Prevent the default action of the page redirection
        e.preventDefault();
    }

    // Else, follow the default action
});

答案 1 :(得分:1)

尝试使用.data()而不是使用计数器污染全局范围

b.click(function(e) {
  if(!$(this).data("flag")) {
    e.preventDefault();
    $(this).data("flag",true);
    t.tooltip('show');
  } else {
    // on second click direct user to value of href 
  }
});