3

我有以下代码将在 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>

我究竟做错了什么?

4

3 回答 3

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')){
             --^^^^^^^^^^^^^^^^^^--
    
于 2012-11-29T18:07:46.397 回答
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/

于 2012-11-29T18:09:00.217 回答
2

试试这个代码:

$(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>');
  })
});​
于 2012-11-29T18:16:39.863 回答