简体   繁体   中英

How can I write this function without using a modulo?

I'm wondering if there is another way to write this function without using a modulo. I realized that I have another piece of code that requires me to click the #mail-wrap button and doing so messes up the number of clicks which affects this function.

It's just a simple switch. I'm not too good with conditionals.

$('#mail-wrap').click(function (e) {
    e.preventDefault();

    var c = 0;

    if (c++ % 2 == 0) {
        $('#contact-button').addClass('project-button').text('Projects');
    } else {
        $('#contact-button').removeClass('project-button').text('Get in touch');
    }
});

Edit: Changed the question a bit. Sorry, the last one was too broad.

As Boldewyn mentioned, most likely your problem is that you are defining a global variable c . But if you would like to avoid this variable completely you could check for the CSS-class of contact-button via the jQuery hasClass function, ie

$('#mail-wrap').click(function (e) {
  ...
  var contactButton = $('#contact-button');

  if (!contactButton.hasClass('project-button')) {
    $('#contact-button').addClass('project-button').css('width', '71px').text('Projects');
    ...
  } else {
    $('#contact-button').removeClass('project-button').css('width', '96px').text('Get in touch');
    ...
  }
});

The code is interfering with other code, because you have implicitly generated a global variable c . Possible fix: Use an IIFE :

(function() {
  var c = 0;
  /* rest of your code above ... */
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM