2012-03-20 11 views
1

我有jQuery的foreach循環通過每個 'div.panel' 走,我需要這個div內訪問圖像的IMG SRC ...jquery如何訪問imr src?

HTML:

<div class="panel" title="Sean Gay"> 
    <div class="wrapper"><img src="/Media/people/SeanGay.jpg" alt="Sean Gay" class="person"> 
     <div class="vcard"><span class="fn">Sean Gay</span> <span class="title">Chief Storeman</span> 
     </div> 
</div> 
</div> 

的jQuery:

jQuery(this).find("div.panel").each(function(n) { 
    var title = jQuery(this).attr("title"); 

這讓我的面板的標題,在這個循環內我需要包裝的圖像的src沒有.jpg擴展名。

我怎樣才能做到這一點?

+0

變化'title'爲'src'然後執行字符串操作 – scibuff 2012-03-20 14:10:56

回答

2

這僅僅是基本的遍歷字符串操作:

jQuery(this).find("div.panel").each(function(n) { 
    // Get the panel as a jQuery instance 
    var panel = jQuery(this); 

    // Get its title 
    var title = panel.attr("title"); 

    // Find the first image and get its `src` property; note that here 
    // I'm assuming there *will* be one. If that assumption isn't true, 
    // cache the img lookup and use `if (img[0])` to guard. 
    var src = panel.find("img")[0].src; 

    // Remove ".jpg" at the end if it's there 
    src = src.replace(/\.jpg$/i, ""); 
}); 
1
$(function(){ 


    $("div.panel").each(function(n){ 
    var imageSrc=$(this).find("img").attr("src");  
    var ary = imageSrc.split("/"); 
    var onlyFileName=ary[ary.length - 1]; 
    var imageSrcWithioutExtension=onlyFileName.replace(".JPG", "").replace(".jpg", "");; 
    alert(imageSrcWithioutExtension) 
    }); 
}); 

這裏是工作樣例:http://jsfiddle.net/QSgtg/24/