jquery如何访问imr src?

时间:2012-03-20 14:07:19

标签: jquery

我在jQuery中有一个foreach循环遍历每个'div.panel',我需要在这个div中访问图像的img 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扩展名。

我该怎么做?

2 个答案:

答案 0 :(得分: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 :(得分: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/