0

我有看起来像这样的简单 html:

<div class="img">
      <a target="_blank" href="kl_big.htm" id="turn-of-cloth-01_lg">
      <img src="images/galery/turn-of-cloth-01_lg.jpg"   width="110" height="90" />
      </a>
      <div class="desc">Add a description of the image here</div>
    </div>

我有 20 组具有不同 id 的这个 div,现在这个 href id 和这个

$(document).ready(function(){
    $('a').click(function (event){

        event.preventDefault();
        var linkID =$(this).attr("id"); 
    });
});

我不知道 img 对象 id 是什么,但我需要获取它的 src 值。我试过这样的Jquery:

var imgSrcVal = $(this).siblings("img").attr("src");

但没有结果,也在点击事件中尝试过,但再次没有结果:

imgSrcVal = this.nextSibling.src;   

我在这里做错了什么?

4

4 回答 4

6

<img>不是兄弟姐妹,它是锚的孩子。

试试这个:

$('a').click(function (event){
    var linkID = $(this).attr("id"); 
    var imgSrcVal = $('img', this).attr("src");
    //alert(imgSrcVal);
    return false;
})

简单的 JSFiddle 演示

于 2011-12-02T23:08:29.557 回答
3

img是嵌套的,所以使用.find()or .children()

var imgSrcVal = $(this).find("img").attr("src");
  • .find()看着所有的后代

  • .children()只看直系后代


或者使用原生 DOM 方法:

var imgSrcVal = this.getElementsByTagName('img')[0].src;

[0]是因为getElementsByTagName返回一个类似数组的集合。所以[0]得到找到的第一个元素。

于 2011-12-02T23:08:31.950 回答
3

我想这就是你想要的。该图像是锚标签的子标签,而不是兄弟标签。

  $('a').click(function (event){
        event.preventDefault();
        var linkID =$(this).attr("id"); 
         alert($(this).children('img').attr('src'))
    });

看看这个小提琴

于 2011-12-02T23:10:30.453 回答
2

img示例中的标签不是标签的兄弟a,它是一个孩子。所以要获得src属性的值,你会做$(this).children("img").attr("src")

于 2011-12-02T23:09:39.440 回答