在点击事件中,首次点击时触发代码一次,剩余代码在所有点击上运行

时间:2016-05-09 16:11:08

标签: javascript jquery

如何只在第一次点击按钮时运行一段代码,还要在所有点击上运行剩余的代码?

$button.click(function (e) {
    // Only run on first click
    $element.removeClass('mobile').addClass('desktop');
    // Run on every click   
    $elementTwo.show()
});

2 个答案:

答案 0 :(得分:2)

只需使用布尔标志变量

var st = true;
$button.click(function(e) {
  // this line only execute once, since after first execution `st` will update to false
  st && $element.removeClass('mobile').addClass('desktop') && st = false;
  $elementTwo.show()
});

答案 1 :(得分:1)

使用jQuery' one()方法:

$button.one('click', function() { //this will run only on the first click
  $element.removeClass('mobile').addClass('desktop');
});

$button.click(function() {  //this will run for every click
  $elementTwo.show();
});
相关问题