2

有一个简单的问题!我有一个结构像这样的代码:

    <a class="adv_link" target="_blank" href="">Link 1</a>
    text here 1
    <div class="adv_separator"></div>

    <a class="adv_link" target="_blank" href="">Link 2</a>
    text here 2
    <div class="adv_separator"></div>

and etc...

我想在每个链接之前添加带有“add_link”类的代码:<div class="slide">并在每个div之后添加带有“adv_separator”类的代码:</div>我怎么能用jquery做到这一点?

ps 换句话说,我想创建几个嵌套这些链接、文本和 div 的 div,这样我就可以使用 jquery 循环插件来创建一个滑块。

谢谢大家的帮助!

4

2 回答 2

4

简单的逻辑,但你必须知道 DOM 是如何工作的。(追加“移动”元素,没有“稀疏选择器”,你需要知道在哪里放置新元素等)

$('.adv_link').each(function() {
    var el = $('<div></div>', {'class': 'slide'}),
        link = $(this),
        text = $(this.nextSibling),
        sep = link.nextUntil('.adv_separator');

    // Append each element. Cloned elements, of course.
    el
        .append(link.clone())
        .append(text.clone())
        .append(sep.clone());

    // Remove the separator and the text.
    sep.remove();
    text.remove();

    // And replace the link with the full div containing the cloned elements.
    link.replaceWith(el);            
});
于 2013-01-30T09:35:20.013 回答
4

非常简短的版本:

$(".adv_link").each(function() {
    $(this).nextUntil(".adv_separator +")
      .andSelf().add(this.nextSibling)
      .wrapAll("<div class='slide' />");
});

演示:http: //jsbin.com/ukafip/2/

于 2013-01-30T09:38:35.450 回答