jQuery内容分离

时间:2012-02-03 22:50:49

标签: javascript jquery

我有以下结构:

<div class="cardapio-content">
    <h5>Tittle of tab 1</h5>
    <p>Content of tab 1</p>
    <h5>Tittle of tab 2</h5>
    <p>Content of tab 2</p>
    <h5>Tittle of tab 3</h5>
    <p>Content of tab 3</p>
</div>

并希望获取每个h5并添加到另一个div <div class="cardapio-menu">,将p下方的h5内容与每个标签相关联。

我尝试使用each,但不知道如何将p相对于h5索引...

jQuery('.cardapio-content h5').each(function(k, v) {
    alert(jQuery('.cardapio-content')[k].html());
})

感谢。

3 个答案:

答案 0 :(得分:4)

只需使用.next()

jQuery('.cardapio-content h5').each(function(){
    var h5 = $(this);
    var p = $(this).next();
});

http://api.jquery.com/next

答案 1 :(得分:2)

使用jQuery的.eq来获取你想要的元素。

jQuery('.cardapio-content h5').each(function(k, v) {
    alert(jQuery('.cardapio-content p').eq(k).html());
})

答案 2 :(得分:1)

DEMO jsBin

仅在each函数中使用了.next().andSelf()选择器,将它们包装在一起:

$('.cardapio-content h5').each(function(){
  $(this).next('p').andSelf().wrapAll('<div class="cardapio-menu" />');
});