使用jQuery只瞄准一个元素

Target only one element with jQuery

本文关键字:一个 元素 jQuery 使用      更新时间:2023-09-26

我的代码有这个小问题,我想Stack Overflow的家伙可能知道如何解决这个问题。

情况是这样的:

我需要在p内附加strong到另一个元素,这将是帖子标题。我已经能够创建解决方案,但我有问题。图片说明复制到其他相同的命名元素,我不希望发生。所以post可能有图片说明,但并不总是这样,但它仍然需要工作。

HTML

<div class="post">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ornare erat sit amet nulla  faucibus pharetra. Donec in mauris lorem. Pellentesque egestas aliquet lobortis. Praesent molestie.</p>
</div>
<div class="post">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ornare erat sit amet nulla faucibus pharetra. Donec in mauris lorem. Pellentesque egestas aliquet lobortis. Praesent molestie.</p>
</div>
<div class="post">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ornare erat sit amet nulla faucibus pharetra. Donec in mauris lorem. Pellentesque egestas aliquet lobortis. Praesent molestie.</p>
  <p><strong>This is a caption.</strong></p>
</div>

JS

var $caption = $(".post strong:first-child").text();
var $removable = $(".post strong:first-child");
$(".post strong:first-child").parent().remove();
$removable.remove();
$(".post").append("<p class='post-caption'>" + $caption + "</p>");

代码片段:

http://codepen.io/aleksitappura/pen/auvrE

我很感激你的帮助。

$(".post strong:first-child").parent().remove();表示每个.post中的第一个strong

如果你只想要第一个.post,你可以选择$('.post').first().find('strong');$('.post:first-child strong');

对于多个strong标记,您可以尝试以下演示:

http://jsfiddle.net/lotusgodkk/7mP8Y/1/

JS:

var i = $(".post strong:first-child");
i.each(function () {
    var elem = $(this);
    var post = elem.parents('.post:first');
    var $caption = elem.text();
    elem.parent().remove();
    post.append("<p class='post-caption'>" + $caption + "</p>");
});

DEMO

你需要保存一个引用到source,这样你就可以在那里返回标题:

var $caption = $(".post strong:first-child").text();
var $removable = $(".post strong:first-child");
//SAVE A REFERENCE TO THE SOURCE/TARGET
var $source = $removable.closest('.post');
$(".post strong:first-child").parent().remove();
$removable.remove();
//ADD TO SOURCE/TARGET
$source.append("<p class='post-caption'>" + $caption + "</p>");

如果你的目标是一个以上的元素,你可以使用.each如下所示,每个元素都会自己改变:

$(".post strong:first-child").each(function() {
    var $caption = $(this).text();
    var $parent = $(this).closest('.post');
    $(this).parent().remove();
    $parent.append("<p class='post-caption'>" + $caption + "</p>");
});

按如下方式更新jquery代码

 var $caption = $(".post strong:first-child").text();
 var $removable = $(".post strong:first-child");
 $(".post strong:first-child").parent().append("<p class='post-caption'>" + $caption + "</p>");
 $removable.remove();

编辑

如果你想在所有的post部分都这样做,那么你必须使用each函数,如下所示。

 $(".post").each(function(){  
 var $caption = $(this).find("strong:first-child").text();
 $(this).find("strong:first-child").parent().append("<p class='post-caption'>" + $caption + "</p>");
 $(this).find("strong:first-child").remove();
 });

以及接下来