【问题标题】:limit x value during increment / decrement with jQuery previous & next button使用jQuery上一个和下一个按钮在递增/递减期间限制x值
【发布时间】:2013-02-23 15:18:56
【问题描述】:

主图像下方有上一个和下一个按钮,有 x 张照片(在本例中为 7 张),我需要限制添加到 x 数量的值,使其只能在 1 到x(在这种情况下为 1 到 7)。

显然当用户到达 x 时,点击下一步应该回到 1。

问题可以看这里:http://mylandscapes.splintertaeal.com/gardens/regents-park.htm

任何帮助将不胜感激。

代码:

$(document).ready(function () {
  var el = $('.nr');

  function change(amt) {
    el.text(parseInt(el.text(), 10) + amt);
  }

  $('#next').click(function () {
    change(1);
  });

  $('#prev').click(function () {
    change(-1);
  });
});

【问题讨论】:

  • 请编辑您的问题并添加相关代码。就目前而言,这个问题是一个教科书非建设性问题

标签: jquery increment decrement


【解决方案1】:

我会说你应该完全删除这段代码:

$(document).ready( function() {
    var el = $('.nr');
    function change( amt ) {
        el.text( parseInt( el.text(), 10 ) + amt );
    }
    $('#next').click( function() {
        change( 1 );
    });
    $('#prev').click( function() {
        change( -1 );
    });
});

改为修改以下事件处理程序。

var $nr = $(".nr");
$('#next, #prev').on('click', function() {
    var A = this.id == 'next',X=A?T:0,Y=A?0:T,Z=A?N+1:N-1;N=N==X?Y:Z;
    $("#display").html('<img src="'+$(E[N]).attr('href')+'" />');
    $(".display2").html('<img src="'+$(F[N]).attr('href')+'" />');
    /* Update the slide number */ 
    $nr.text(N + 1);
});

在这种情况下不需要有两个事件处理程序。

【讨论】:

  • 似乎可以正常工作,但现在除非单击按钮,否则不会加载图像
  • @splinterteal,你删除了错误的代码。我编辑了答案以明确显示您需要删除的代码
【解决方案2】:
        int i = 0
        $(nextbutton).click(function () {
          i++;
          if (i == 7) {
            i = 0;
          }
 showImage(i); // get i indexed image from array
        });

        $(prevbutton).click(function () {
          i--;
          showImage(i); // get i indexed image from array
          if (i == 0) {
            return;
          }
        });

I hope I understood your problem  in a right way .

【讨论】:

  • 在 next.click showImage() 函数应该在 if 语句之后,而不是在里面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2021-08-14
  • 1970-01-01
  • 2014-01-10
相关资源
最近更新 更多