【问题标题】:Move element to closest other element with class将元素移动到具有类的最近的其他元素
【发布时间】:2019-03-22 02:07:15
【问题描述】:

我在页面上有多篇文章,但我想将 h2 标题移动到(最近的)flexslider div 中,因为我想要图像上的标题,但我无法让它工作。

HTML:

<article>
    <div class="flexslider"></div>
    <div class="post-content">
        <h2 class="entry-title">Title text</h2>
    </div>
</article>

我想要什么:

<article>
    <div class="flexslider">
        <h2 class="entry-title">Title text</h2>
    </div>
    <div class="post-content"></div>
</article>

JS 对我不起作用:

jQuery('article h2.entry-title').appendTo( jQuery('.flexslider') );

【问题讨论】:

    标签: jquery move closest


    【解决方案1】:

    试试这个...

    $("#appendTo").click(function() {
      $(".entry-title").appendTo($(".flexslider"));
    });
    $("#prependTo").click(function() {
      $(".entry-title").prependTo($(".flexslider"));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="flexslider" >sss</div>
        <div class="post-content" >
            <h2 class="entry-title">Title text</h2>
        </div>
        <button id="appendTo">appendTo main</button>
    <button id="prependTo">prependTo main</button>

    【讨论】:

    • 当你有多个 .flexslider 元素时会发生什么?
    【解决方案2】:

    您可以使用append( function )。对于每个.flexslider,在同一个&lt;article&gt; 中找到.entry-title 并附加它:

    $( '.flexslider' ).append( function() {
        return $( this ).closest( 'article' ).find( '.entry-title' );
    } );
    

    Here's a fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-20
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多