2015-11-21 35 views
0

視圖頁面內我有幾個DIV其ID的開始與my-前綴,訪問兒童屬性值

<div id="my-div1"><img src="/img/1.jpg" /></div> 
<div id="my-div2"><img src="/img/2.jpg" /></div> 
<div id="my-div3"><img src="/img/3.jpg" /></div> 
在js代碼

我迭代槽每一個元素,我想申請某一功能子img元素,在這種情況下,直道

$(document).ready(function() { 
    $('div[id^="my-"]').each(function() { 
     $(this).css("background-size", "100% 100%"); 
     $(this).css("background-repeat", "no-repeat"); 
     // this doesn't work    
     $(this).children("img").backstretch($(this).attr('src')); 
    }) 
}); 

當我測試的每個格下的IMG $(this).children("img").length回報實際數目,但我不知道如何通過它的src屬性值直道功能?

+0

jquery中的後背? –

+0

http://srobbin.com/jquery-plugins/backstretch/ – user1765862

回答

3

基於the documentation,它看起來並不像backstretch支持函數傳遞(的方式可能的jQuery setter函數做的),所以你堅持each

$(this).children("img").each(function() { 
    $(this).backstretch(this.src); 
}); 

請注意,我不打擾使用jQuery來訪問src,那裏已經有一個DOM屬性準備好了,正在等待。 :-)

或者,如果你想申請backstretchDIV,因爲每個div都只有一個形象,你可以這樣做:

$(this).backstretch($(this).find("img").attr("src")); 

attr將返回第一個圖像的src div。

最後,由於backstretch支持多種圖像爲幻燈片放映時,如果您的div將會有一個以上的圖像,你可以使用children("img").map(...).get()得到他們src 屬性的數組:

$(this).backstretch($(this).children("img").map(function() { 
    return this.src; 
}).get()); 
+1

這應該被視爲一個完美的答案。我只能投1x。 – user1765862

0

試試這個:

$(document).ready(function() { 
    $('div[id^="my-"]').each(function() { 
     $(this).children("img").each(function() { 
      $(this).backstretch($(this).attr("src")); 
     }); 
    }) 
}); 
+0

你可能是指'$(this).attr(「src」)'?或者[email protected]。 Crowder只是'this.src' – Arg0n

+0

@ Arg0n,你確實是對的。改變了它。謝謝! – Berendschot