在图像的元素标记之前插入div

时间:2012-11-29 17:55:27

标签: jquery

我有以下代码,它将在div中查找并查找所有图像。然后它将图像包装在一个新的div中,创建一个包含按钮的第二个div,这用于使用另一个脚本执行图像悬停效果

$(document).ready(function(){
    // Get the images from whatever element contains them.    
    var postImgs = $('#primary img');

    postImgs.each(function applyPinterestButton(){

    // This allows the post-writer to add a class of "nopin" to
    // whatever images they don't want to have pinned.
    if($(this).attr('class').indexOf('nopin') == -1){       
        // Wrap the image in a container.
        $(this).wrap('<div class="showPin"/>');         

        // Add the pinterest button and link into the container.
        $(this).parent().prepend('<div class ="pinIt"><a href="buttonlink.html" target="_blank"><img src="button.jpg" /></a></div>');           
    }
});

之前的jQuery html看起来像这样:

<a href="http://originalimagelink.html"><img src="originalimage.jpg"></a>

但是在脚本之后,jquery只包装了img,如下所示:

<a href="originalimagelink.html">
<div class="showPin">
    <div class="pinIt">
        <a href="buttonlink.html">
            <img src="button.jpg">
        </a>
    </div>
    <img src="originalimage.jpg">
</div>
</a>

我需要它来包装imga元素。所以最终结果是这样的:

<div class="showPin">
    <div class="pinIt">
        <a href="buttonlink.html">
            <img src="button.jpg">
        </a>
    </div>
    <a href="originalimagelink.html"><img src="originalimage.jpg"></a>
</div>

我做错了什么?

3 个答案:

答案 0 :(得分:4)

  1. 您可能想要从图片的父元素开始。

    // Get the images from whatever element contains them.    
    var postImgs = $('#primary img').parent();
                                  --^^^^^^^^^--
    
  2. 您可以使用.hasClass()功能。

    // This allows the post-writer to add a class of "nopin" to
    // whatever images they don't want to have pinned.
    if(!$(this).hasClass('nopin')){
             --^^^^^^^^^^^^^^^^^^--
    

答案 1 :(得分:2)

试试这段代码:

$(document).ready(function(){
  // Get the images from whatever element contains them.    
  var postImgs = $('#primary img');
  postImgs.each(function() {

  // This allows the post-writer to add a class of "nopin" to
  // whatever images they don't want to have pinned.
  if(!$(this).hasClass('nopin')) {      

    // Wrap the image in a container.
    $(this).parent().wrap('<div class="showPin"/>');         

    // Add the pinterest button and link into the container.
    $(this).parent().parent().prepend('<div class ="pinIt"><a href="buttonlink.html" target="_blank"><img src="button.jpg" /></a></div>');           

  }
  });
});
​

演示:http://jsfiddle.net/gfE7m/2/

答案 2 :(得分:2)

尝试this代码:

$(function(){
    $('img').not('.nopin').each(function(){
        $(this).closest('a').wrap('<div class="showPin"/>').before('<div class="pinIt"><a href="buttonlink.html"><img src="button.jpg"></a></div>');
  })
});​