简体   繁体   中英

How to use this JavaScript snippet twice on the page?

With some help, I got some JavaScript working. It looks like:

<script>
  $(document).ready(function() {
    var $li = $('.eo-events li');

    $li.hide().filter(':lt(6)').show()

    var x = 6;

    $('#next, #prev').click(function() {
      var m = this.id === 'prev' ? 'first' : 'last';
      var $m = $li.filter(':visible')[m]()[this.id + 'All'](":lt(" + x + ")");
      if ($m.length == 0) return;

      var time = 250;

      $li.fadeOut(time);
      setTimeout(function() {
        $m.fadeIn(time);
      }, time);
    });
  });
</script>

What this does is take a group of list items and navigate every 5 list items.

This is working great, but I'd like to use this as-is and then also somewhere else, is that possible? I tried adding another script call which looks like this. The top part functions, which only shows a certain number of items, but the next and prev arrows are not functioning at all. The original set of list items is still working great, even with this second script call, but I'm not sure why the second set of next and prev arrows are not working.

<script>
  $(document).ready(function() {
    var $li = $('.new-list li');

    $li.hide().filter(':lt(1)').show()

    var x = 1;

    $('#next1, #prev1').click(function() {
      var m = this.id === 'prev1' ? 'first' : 'last';
      var $m = $li.filter(':visible')[m]()[this.id + 'All'](":lt(" + x + ")");

      if ($m.length == 0) return;

      var time = 250;

      $li.fadeOut(time);
      setTimeout(function() {
        $m.fadeIn(time);
      }, time);
    });
  });
</script>

I'm thinking I need to change a variable name. I have tried changing x to y and m to n and $li to $item , but it's not working. I know this is probably a simple adjustment, any ideas?

you over complicated this line:

var $m = $li.filter(':visible')[m]()[this.id + 'All'](":lt(" + x + ")");

making it hard to spot problems

It would appear you are wanting to chain methods nextAll() or prevAll() but since the ID's you are using in second instance have a 1 at the end you will end up with next1All() or prev1All() . These should be throwing errors indicating method doesn't exist

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