jQuery -选择相同的元素并将它们移动到自己的父元素中

jQuery - Select same elements and move them into their own parents

本文关键字:元素 移动 自己的 选择 jQuery      更新时间:2023-09-26

我目前正在做一个基于WordPress的网站。我想使用jQuery来移动博客文章的日期。我无法编辑这个模板,因为它被用在其他页面上了。

确切地说,我想把。entry-time元素移到。entry-title 下面

下面是HTML代码:

<div class="post-content-container">
    <h2 class="entry-title">Blog 1</h2>
    <div class="entry-meta">
        <p class="entry-meta-details">
            <span class="entry-time">
                <span class="updated" style="display:none;">2014-06-24T13:58:52+00:00</span>
                <time class="published">June 24th, 2014</time>
            </span>
        </p>
</div>
<div class="post-content-container">
    <h2 class="entry-title">Blog 2</h2>
    <div class="entry-meta">
        <p class="entry-meta-details">
            <span class="entry-time">
                <span class="updated" style="display:none;">2014-06-20T13:58:52+00:00</span>
                <time class="published">June 20th, 2014</time>
            </span>
        </p>
</div>
<div class="post-content-container">
    <h2 class="entry-title">Blog 3</h2>
    <div class="entry-meta">
        <p class="entry-meta-details">
            <span class="entry-time">
                <span class="updated" style="display:none;">2014-05-20T13:58:52+00:00</span>
                <time class="published">May 20th, 2014</time>
            </span>
        </p>
</div>
下面是我目前使用jQuery所做的:
jQuery(".post-content-container").find(".entry-time").each(function(){
            jQuery(this).appendTo(".entry-title");
    });

元素"。"入门时间"在正确的位置,但我的循环有问题。三个日期显示在每个博客标题下:

https://i.stack.imgur.com/FCA8G.png

你能帮我修理这个循环吗?

谢谢,Damien

这是因为您在.appendTo(".entry-title")中的选择器每次都匹配所有三个条目标题。您需要的是只匹配每个特定.entry-time的相关标题。为此,一种方法是将DOM导航到正确的目标,例如:

jQuery(".post-content-container").find(".entry-time").each(function(){
    var $this = jQuery(this);
    $this.appendTo($this.closest(".post-content-container").find(".entry-title"));
});

当然,当你看它之后,它邀请拉动.each,以便不必遍历DOM多次为同一元素:

jQuery(".post-content-container").each(function() {
    var $this = jQuery(this);
    $this.find(".entry-time").appendTo($this.find(".entry-title"));
});

我真的更喜欢这个进化的版本:回调的主体读起来非常接近自然语言。

您没有选择与当前项目对应的特定.entry-title

jQuery(".post-content-container").find(".entry-time").each(function(){
    jQuery(this).appendTo($(this).closest(".entry-meta").prev(".entry-title"));
});