【问题标题】:How do i add a maximum and minimum to a variable in jQuery如何在jQuery中为变量添加最大值和最小值
【发布时间】:2019-05-23 01:17:32
【问题描述】:

我正在制作一个菜单,显示您在我的网站上的哪个部分。我有 3 个圈子可以显示您所在的部分。

如果您点击“向下”,您将进入一个部分,如果您点击“向上”,您将返回一个部分。

现在我做到了,如果您单击“向下”,它会将 1 添加到变量“sectionCounter”,如果您单击向上,它会从中删除 1。

我想添加一个最小值为 1,一个最大值为 3,因为没有更多的部分,我该怎么做?

这是我的 jQuery:

    var sectionCounter = 1;
    sectionCounter == 1;

    $('.down1').click(function() {
        var section2 = $('.section2');
        var pos = section2.offset().top;
        sectionCounter += 1;
        $('h1').html(sectionCounter);

    if (sectionCounter == 1){
        $('.count1').addClass('countActive');
    }else {
        $('.count1').removeClass('countActive');
    };


    if (sectionCounter == 2){
        $('.count2').addClass('countActive');
    }else {
        $('.count2').removeClass('countActive');
    };


    if (sectionCounter == 3){
        $('.count3').addClass('countActive');
    }else {
        $('.count3').removeClass('countActive');
    };


    $('html, body').animate({scrollTop:pos},2000); // will take two seconds to scroll to the element
    });


    $('.up1').click(function() {
        var section1 = $('.section1');
        var pos2 = section1.offset().top;
        sectionCounter -= 1;
        $('h1').html(sectionCounter);

    if (sectionCounter == 1){
        $('.count1').addClass('countActive');
    }else {
        $('.count1').removeClass('countActive');
    };


    if (sectionCounter == 2){
        $('.count2').addClass('countActive');
    }else {
        $('.count2').removeClass('countActive');
    };


    if (sectionCounter == 3){
        $('.count3').addClass('countActive');
    }else {
        $('.count3').removeClass('countActive');
    };

    $('html, body').animate({scrollTop:pos2},2000); // will take two seconds to scroll to the element
    });

【问题讨论】:

  • 旁注:不要将;放在附加到控制流语句的块之后(ifelsewhileforswitch) .这样做是无害的(因为 JavaScript 有 EmptyStatement,这实际上意味着它会忽略无关的 ;s),但也毫无意义。

标签: javascript jquery variables max min


【解决方案1】:

你有几个选择:

您可以使用if

if (sectionCounter < 3) {
    sectionCounter += 1; // Side note: `++sectionCounter;` or `sectionCounter++;` would be more idiomatic
}

-= 1 的情况类似:

if (sectionCounter > 1) {
    sectionCounter -= 1; // Side note: `--sectionCounter;` or `sectionCounter--;` would be more idiomatic
}

您可以(ab)使用&amp;&amp; 运算符:

sectionCounter < 3 && ++sectionCounter;

对于-= 1 案例也是如此:

sectionCounter > 1 && --sectionCounter;

这些工作是因为如果左侧操作数为真(或者更确切地说,truthy),则不会评估右侧操作数。

你可以使用Math.min/Math.max:

sectionCounter = Math.min(3, sectionCounter + 1);

sectionCounter = Math.max(1, sectionCounter - 1);

【讨论】:

  • 我把最后一个选项放在'var sectionCounter = 1;'下但这似乎对我不起作用。
  • @rutgervs - 重点是在您执行 +=-= 时执行此操作,而不是在声明变量后立即执行此操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多