简体   繁体   English

如何在不使用模数的情况下编写此函数?

[英]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. 我意识到我还有另一段代码,要求我单击#mail-wrap按钮,这样做会使影响此功能的单击次数混乱。

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 . 正如Boldewyn所述,您最有可能遇到的问题是正在定义全局变量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 但是,如果您想完全避免使用此变量,则可以通过jQuery hasClass函数检查contact-button的CSS类,即

$('#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 . 该代码正在干扰其他代码,因为您已隐式生成了全局变量c Possible fix: Use an IIFE : 可能的解决方法:使用IIFE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用箭头功能的情况下编写此功能? - How can I write this function without using an arrow function? 如何在不使用Angular.js中使用$ apply()的情况下编写此函数 - How can I write this function without using $apply() in Angular.js 如果没有一堆if else语句,我怎么能写这个函数呢? - How can I write this function without a bunch of if else statements? 如何用模优化函数? - How do I optimize a function with modulo? 如何在不使用框架的情况下编写面向对象的Javascript? - How can I write object oriented Javascript without using a framework? 如何在不使用函数参数的情况下将值传递给函数? - How can I pass a value into a function without using function parameters? 我怎么能用javascript(没有jquery)写这个 - how can i write this with javascript (without jquery) 如何使用箭头函数在 forEach 循环中使用 Modulo? - How to use Modulo inside of a forEach loop using arrow function? 如何使用递归求解模(不能使用*,%或/或数学运算符) - How to Solve modulo using recursion(can't use *, %, / or Math operator) 如何在不使用JavaScript或self的情况下在函数内部访问此函数? - how can I access this inside a function without using that or self in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM