如何使用jQuery循环遍历元素?

时间:2015-05-25 09:38:06

标签: jquery html

我有这个jQuery代码作用于某些HTML选项卡,清除content-current类的section元素,然后将content-current类添加到我想要显示的内容中。它还清除了tab-current类的选项卡,并将tab-current类添加到我单击的类中。这段代码本身可以工作并完成我需要的一切:

$('a.tab1').click(function() {
    $('section').removeClass('content-current');
    $('#section-1').addClass('content-current');
    $('a').removeClass('tab-current');
    $('a.tab1').addClass('tab-current');
});

$('a.tab2').click(function() {
    $('section').removeClass('content-current');
    $('#section-2').addClass('content-current');
    $('a').removeClass('tab-current');
    $('a.tab2').addClass('tab-current');
});

$('a.tab3').click(function() {
    $('section').removeClass('content-current')
    $('#section-3').addClass('content-current')
    $('a').removeClass('tab-current');
    $('a.tab3').addClass('tab-current');
});

$('a.tab4').click(function() {
    $('section').removeClass('content-current')
    $('#section-4').addClass('content-current')
    $('a').removeClass('tab-current');
    $('a.tab4').addClass('tab-current');
});

$('a.tab5').click(function() {
    $('section').removeClass('content-current')
    $('#section-5').addClass('content-current')
    $('a').removeClass('tab-current');
    $('a.tab5').addClass('tab-current');
});

显然这是非常重复的,很可能是我对jQuery的讽刺。我已经完成了一些研究,但无法弄清楚如何使用jQuery循环访问HTML集合来重构这一点。我可以在jQuery对象上为每个或lodash使用吗?任何指针或资源都会有所帮助。谢谢!

html代码标签:

<li><a href="#section-1" class="tab1 tab-current"><span>  Shop</span></a></li>
<li><a href="#section-2" class="tab2"><span>  Drinks</span></a></li>
<li><a href="#section-3" class="tab3"><span>  Food</span></a></li>
<li><a href="#section-4" class="tab4"><span>  Lab</span></a></li>
<li><a href="#section-5" class="tab5"><span>  Order</span></a></li>

内容html:

<section id="section-1" class="content-current">
    <div class="mediabox">
        <img src="img/01.png" alt="img01" />
        <h3>Sushi Gumbo Beetroot</h3>
        <p>Sushi gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato.</p>
    </div>
    <div class="mediabox">
        <img src="img/02.png" alt="img02" />
        <h3>Pea Sprouts Fava Soup</h3>
        <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea.</p>
    </div>
    <div class="mediabox">
        <img src="img/03.png" alt="img03" />
        <h3>Turnip Broccoli Sashimi</h3>
        <p>Nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip greens parsnip.</p>
    </div>
</section>
<section id="section-2">
    <div class="mediabox">
        <img src="img/04.png" alt="img04" />
        <h3>Asparagus Cucumber Cake</h3>
        <p>Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd. </p>
    </div>
    <div class="mediabox">
        <img src="img/05.png" alt="img05" />
        <h3>Magis Kohlrabi Gourd</h3>
        <p>Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels sprout chard.</p>
    </div>
    <div class="mediabox">
        <img src="img/06.png" alt="img06" />
        <h3>Ricebean Rutabaga</h3>
        <p>Celery quandong swiss chard chicory earthnut pea potato. Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. </p>
    </div>
</section>
<section id="section-3">
    <div class="mediabox">
        <img src="img/02.png" alt="img02" />
        <h3>Noodle Curry</h3>
        <p>Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea.Sushi gumbo beet greens corn soko endive gumbo gourd.</p>
    </div>
    <div class="mediabox">
        <img src="img/06.png" alt="img06" />
        <h3>Leek Wasabi</h3>
        <p>Sushi gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato.</p>
    </div>
    <div class="mediabox">
        <img src="img/01.png" alt="img01" />
        <h3>Green Tofu Wrap</h3>
        <p>Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut wasabi tofu broccoli mixture soup.</p>
    </div>
</section>
<section id="section-4">
    <div class="mediabox">
        <img src="img/03.png" alt="img03" />
        <h3>Tomato Cucumber Curd</h3>
        <p>Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd. </p>
    </div>
    <div class="mediabox">
        <img src="img/01.png" alt="img01" />
        <h3>Mushroom Green</h3>
        <p>Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels sprout chard.</p>
    </div>
    <div class="mediabox">
        <img src="img/04.png" alt="img04" />
        <h3>Swiss Celery Chard</h3>
        <p>Celery quandong swiss chard chicory earthnut pea potato. Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens nori. </p>
    </div>
</section>

3 个答案:

答案 0 :(得分:4)

一些一般线索

关于您的HTML

  • 我建议永远不要将id用于此目的。如果有人要求您将其中两个选项卡控件放在同一页面上,会发生什么?然后,同事必须修改代码并犯错误并且繁荣,最终会在您的页面上发生碰撞id改为使用数据属性。

关于使用jQuery:

  • 将选择器保存在变量中,而不是始终搜索它们。这将使您的代码更快,并使其看起来更加一致。
  • 将事件处理程序放在包含选项卡的元素上(参见下文)
  • 找到用户点击的元素时,请使用this关键字。然后使用$(this)
  • 将其保存到jQuery变量中

可能的解决方案

假设您有一个.tabcontainer元素,a位于a,且tab有一个a类,而您的data-tabid有一个名为data-tabid的数据属性,用于标识他们指向哪些标签,以及标签本身具有标识它们的var $sections = $("section"); var $allLinks = $(".tabcontainer a.tab"); $('.tabcontainer').on('click', 'a.tab', function() { // Get the <a> you clicked on var $this = $(this); // Get the current tab id var currentTabId = $this.attr('data-tabid'); // Remove class from all sections $sections.removeClass('content-current'); // Find current section var $currentSection = $sections.filter('[data-tabid=' + currentTabId + ']') .addClass('content-current'); // Remove clas from all links $allLinks.removeClass('tab-current'); // Add class to current link $this.addClass('tab-current'); }); 属性,以下是我将如何执行此操作:

<ul class="tabcontainer">
    <li><a href="#section-1" class="tab tab-current" data-tabid="1"><span>Shop</span></a></li>
    <li><a href="#section-2" class="tab" data-tabid="2"><span>Drinks</span></a></li>
    <li><a href="#section-3" class="tab" data-tabid="3"><span>Food</span></a></li>
    <li><a href="#section-4" class="tab" data-tabid="4"><span>Lab</span></a></li>
    <li><a href="#section-5" class="tab" data-tabid="5"><span>Order</span></a></li>
</ul>

以下是我修改你的html的建议:

<section class="content-current" data-tabid="1">...</section>
<section data-tabid="2">...</section>
<section data-tabid="3">...</section>
<section data-tabid="4">...</section>

以及各部分:

request failure with http statusCode:422,exception:org.apache.http.client.HttpResponseException: Unprocessable Entity
request failed with server response:{"name":"PAYMENT_CREATION_ERROR","debug_id":"037a6be490932","message":"checkout-session not created","information_link":"https://api-m.paypal.com/docs/api/#PAYMENT_CREATION_ERROR"}

答案 1 :(得分:0)

更改此标签:

<li><a href="#section-3" class="tab" data-tab-id="3"><span>  Food</span></a></li>

然后你的JS代码看起来像这样:

$(document).on('click', '.tab', function() {
  var sectionId = $.data(this, 'section-id');
  $('.content-current').removeClass('content-current')
  $('#section-' + sectionId ).addClass('content-current')
  $('.tab-current').removeClass('tab-current');
  $(this).addClass('tab-current');
});

文档:$.data().on()

答案 2 :(得分:0)

试试这个:

$('a[class^="tab"]').on('click', function() {
    $('section').removeClass('content-current');
    $($(this).attr('href')).addClass('content-current');
    $('a').removeClass('tab-current');
    $(this).addClass('tab-current');
});
  1. [class^="tab"]:将选择其类以tab开头的所有元素。恩。 tab1tab2
  2. $(this).attr('href'):将获取所点击链接的href属性。恩。第一个链接#section-1
  3. $(this):点击链接