在单击事件中,第一次单击时激发代码一次,其余代码在所有单击时运行

Inside a click event, fire code once on first click, remaining code runs on all clicks

本文关键字:单击 代码 余代码 一次 运行 事件 第一次      更新时间:2023-09-26

如何仅在第一次单击按钮时运行一段代码,同时在所有单击时运行其余代码?

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

只需使用布尔标志变量

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()
});

使用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();
});