1

在一个页面上,我需要检测所有包含图像的条目,并将样式添加到 H1 和 img,以及在这些条目中包含 img 的 p。到目前为止没有问题。

  <div class="entry">
    <h1>Headline</h1>
    <p><img></p>
  </div>

  $("div.entry img").closest(".entry").find("h1").addClass("home-h1-adjust");
  $("div.entry img").closest("p").addClass("home-p-img-adjust");

为了完全解决我面临的问题,我需要分离 h1 或 p,然后重新插入 p 在 h1 之前的位置,这是一系列条目,并非所有条目都有图像。

我被困在循环和预先在jQuery中分离元素的正确方法上。谢谢。

4

4 回答 4

1
$('.entry > p').each(function() {
   $(this).insertBefore(this.previousElementSibling);
});

http://jsfiddle.net/Yr96v/

于 2013-07-14T21:48:36.810 回答
1
//for each entry
$('div.entry').each(function(){
    var $this = $(this);

    //if entry has img
    if($this.find('img').length > 0) {
        //jQuery is chainable, and detaching is done automatically
        $this.find('h1').addClass('home-h1-adjust')
            .before($this.find('p').addClass('home-p-img-adjust'));
    }
});

http://jsfiddle.net/tB8f4/

于 2013-07-14T22:13:54.543 回答
1
$('div.spacer a').addClass('test').each(
   function(){
       $(this).remove();
   }
);

您可以使用.each() 只需打开您的 chrome 控制台并使用它。上面的示例删除了此页面上的每个相关链接。当然可以 var element = $(this).detach();,然后element.appendTo('YOUR POSITION')

于 2013-07-14T22:14:23.133 回答
0

这是有效的解决方案:遍历页面上的所有条目,查找图像,将类附加到 H1 和第一个 p 标记。在 H1 上方添加包含图像的 p,作为条目 div 的第一个子项。

  <div class="entry">
     <h1>Headline 1</h1>
     <p><img />Image? Yes</p>
     <p>Some Text that needs to stay put</p>
     <p>More copy text</p>
  </div>

  <div class="entry">
     <h1>Headline 2</h1>
     <p>Text in a non image entry</p>
     <p>This text has no image to keep it company</p>
  </div>


  $('div.entry').each(function(){
     var $this = $(this);
     if($this.find('img').length > 0) {
        $this.find('h1').addClass('home-h1-adjust');   
        var $img = $this.find('p').first().addClass('home-p-img-adjust');
        $this.prepend($img);
    }
  });

http://jsfiddle.net/lockedown/vkeeD/1/

于 2013-07-15T01:22:06.327 回答