2012-01-06 106 views
0

需要一些幫助。我有一個圖像的div。Jquery:幫助。包裝圖像

<div id="thumbs" class="navigation"> 
    <ul class="thumbs"> 
    <p> 
     <img src="assets/images/example-1.jpg" alt="" width="600" height="400" />  
     <img src="assets/images/example-2.jpg" alt="" width="600" height="400" /> 
     <img src="assets/images/example-3.jpg" alt="" width="600" height="400" /> 
     <img src="assets/images/example-4.jpg" alt="" width="600" height="400" /> 
     <img src="assets/images/example-5.jpg" alt="" width="600" height="400" /> 
     <img src="assets/images/example-6.jpg" alt="" width="600" height="400" /> 
     <img src="assets/images/example-7.jpg" alt="" width="600" height="400" /> 
    </p> 
    </ul> 
</div> 

我需要讓所有的圖像,與href作爲圖像的src包起來錨<a href="">,然後包裹每一個內的<li>

這是我到目前爲止:

var b = $('#thumbs > .thumbs'); // Get a reference to the banner div 
    var i = b.find('img'); // Pull all the images 
    var src = i.attr('src'); 
    b.empty().append(i); // Empty the banner div, and replace the images 
    b.find('img').wrap('<li><a href="' + src + '" /></li>'); // Wrap the images 

這種類型的作品,但我有一個頁面上的多個div,各自具有不同的圖像,jQuery的,現在從每個格拉的所有圖像,並加入他們一起。所以基本上我需要這個jQuery每一個人<div>

回答

0

包裝你的功能是這樣的...

$.fn.ParseImages = function() { 
    $(this).each(function() { 
     var b = $(this).find('#thumbs > .thumbs'); // Get a reference to the banner div 
     var i = b.find('img'); // Pull all the images 
     var src = i.attr('src'); 
     b.empty().append(i); // Empty the banner div, and replace the images 
     b.find('img').wrap('<li><a href="' + src + '" /></li>'); // Wrap the images 
    }); 
}; 

然後調用這樣的代碼...

$(function() { 
    $("div.navigation").ParseImages(); 
}); 

將運行功能在每一個與「導航」類的div。

+0

嗨。這似乎並不奏效。我在我的函數調用之前放置了代碼的頂部,然後是函數調用的第二部分,因爲我使用了其他的JQuery。 – Guy 2012-01-06 13:55:57

+0

我剛剛對頂級代碼做了輕微更改,因此請嘗試更新它。另外,當你添加第二位代碼時,確保你只需添加中間行。不知道你是否知道,但是外部部分 - $(function()等)只是爲了在文檔加載時運行它。 – Archer 2012-01-06 13:57:23

+0

嗨。仍然沒有工作我害怕,我按照你說的去做。文檔之外的頂級代碼準備就緒,文檔就緒函數中的最底層代碼 – Guy 2012-01-06 14:02:21

0

我可以建議作出一個jQuery的功能,就像@Archer那樣,在his answer,如:

$.fn.imgTidy = function() { 
    // finds the images within the child '.thumbs' div of $(this). 
    var images = $(this).find('.thumbs img'); 
    var iLength = images.length; 

    // iterates through each of the resulting image nodes, wrapping each in an 'li' element 
    $(images).each(
     function(){ 
      $(this).wrap('<li></li>'); 
     }); 

    /* if the parent node of the first 'li' element (assuming they all share a common 
     parent, so nested lists are going to be problematic with this approach) is 
     _not_ a 'ul' this unwraps all the list elements returned by the 
     '$('.thumbs li')' selector */ 

    if($('.thumbs li:first').parent().not('ul')){ 
     $('.thumbs li').unwrap(); 
    } 

    // returns the node(s) for chaining. 
    return $(this); 
}; 

,把它作爲這樣的:

$('#thumbs').imgTidy(); 

JS Fiddle demo