3

Using jQuery's .one event handler to do a setup on the first click and something else on the next/subsequent clicks, is it possible to do write this more elegantly:

$('#start').one('click', function(){
    alert('one');

    // could also be .on for subsequent clicks
    $(this).one('click', function(){
        alert('two');    
    });

});

Example fiddle

Update: I was hoping that there was a jQuery pattern to using .one like this self-defining function, but reading the source for .one() it's just an extension of .on()

4

3 回答 3

1
var clickIndex = 0;
$('#start').on('click', function(){
    alert(++clickIndex);
});

您可以在此处放置一个switch语句或一个if块以根据用户单击的次数运行不同的代码。如果.one侦听器取消绑定对您来说很重要,只需使用.offwhenclickIndex表示您已完成绑定。

于 2013-04-11T14:05:07.400 回答
0

也许是这样的:

$('#start').on('click', function(){
    var click = $(this).data('clicked')?$(this).data('clicked'):1;
    alert(click);
    if(click === 2)
        $(this).off('click')
    else $(this).data('clicked',++click);    
});
于 2013-04-11T14:15:38.630 回答
0

我认为在这种情况下,您可以只使用数据属性或类并使用点击事件:

$('#start').on('click', function(){
    if (!$(this).data('clicked')) {
      alert('one');
      $(this).data('clicked', 'true');
    }
    else  {
      alert('more than one');
    }
});

或上课:

$('#start').on('click', function(){
    if (!$(this).hasClass('clicked')) {
      alert('one');
      $(this).addClass('clicked');
    }
    else  {
      alert('more than one');
    }
});
于 2013-04-11T14:00:21.563 回答