JQuery在无序列表中查找下一个类

时间:2014-03-06 23:32:36

标签: javascript jquery html ajax

我在我的网站上使用JQuery / Ajax来实现某些功能。目前我有一个显示无序列表的左侧,每个列表元素都有一个类似于shop-thumb的类,每当点击一个商店拇指然后在右边,内容加载了Ajax。

现在我想要合并下一个/上一个按钮,以便用户可以单击下一个(从右侧),下一个列表项将加载ajax,更改右侧的内容。

以下是我正在使用的基本版本:

<div class="thumbs">
    <ul class="products">
        <li class="shop-thumb"><a href="www.google.com/123"><img src="www.google.com/image1" /></a></li>
        <li class="shop-thumb"><a href="www.google.com/456"><img src="www.google.com/image2" /></a></li>
        <li class="shop-thumb"><a href="www.google.com/789"><img src="www.google.com/image3" /></a></li>
        <li class="shop-thumb"><a href="www.google.com/101112"><img src="www.google.com/image4" /></a></li>
        <li class="shop-thumb"><a href="www.google.com/131415"><img src="www.google.com/image5" /></a></li>
    </ul>
</div>

<div class="paginate">
    <div class="prev">Prev</div> | <div class="next">Next</div>
</div>

<div class="main">
<!-- Ajax comes in here -->
</div>

以下是我在JQuery / Ajax调用中的内容 - 除了.next点击功能外,一切正常:

<script>
jQuery(document).ready(function($){
    var defaultValue = $("ul.products li.shop-thumb a:first").attr("href");

    $(".main").load(defaultValue);

  $("ul.products li.shop-thumb a").click(function(e){
      e.preventDefault();

      var addressValue = $(this).attr("href");
    $(".main").load(addressValue);

  });

  $(".next").click(function() {
      $("ul.products").next();
      var newValue = $("ul.products .shop-thumb a").attr("href");
      $(".main").load(newValue);
  });

});
</script>

如何获得下一个/上一个功能,我们将不胜感激。我以为我应该使用.next().find().nextAll

如果你不介意向我扔骨头并向我展示一个例子,那么我就可以看到我做错了哪里和哪些。

1 个答案:

答案 0 :(得分:2)

您需要为当前项目添加标记,以找出下一个项目的内容。找到下一个项目后,您只需触发该项目上的click事件即可调用处理程序

您可以使用类似

的类
jQuery(document).ready(function ($) {
    $("ul.products li.shop-thumb a").click(function (e) {
        e.preventDefault();

        var addressValue = $(this).attr("href");
        $(".main").load(addressValue);

        //remove the active class from previous item
        $("ul.products li.active").removeClass('active');
        //add the active class to the current li element
        $(this).closest('li').addClass('active');
    });

    $(".next").click(function () {
        //find the next item and trigger the click event
        $("ul.products li.active").next().find('a').trigger('click');
    });

    //default loading
    $("ul.products li.shop-thumb a:first").click();

});