如果锚标签中有图像标记,如何获取锚标记的href值

时间:2013-07-09 07:08:46

标签: javascript jquery jquery-selectors

我试图用jquery获取图像src,这是下面的代码

jQuery("img").click(function() {
    var im = $(this).attr('src'); 
    alert(im);
    return false;
});

以上工作正常我可以得到图像src。同样我试图获得锚标签的href值只有它有一个图像标签,否则它不应该.Below是一个包含图像标签的例子。

<a href="some.something"><img src="image1.jpg"></a>

如何做到这一点?什么选择器更好?任何想法?

2 个答案:

答案 0 :(得分:4)

$('img').parent('a') // Will select anchors who are `img` elements parents. 

$('img').parent('a').each(function(_,el){console.log(el.href)}); // will take the href attr.

使用点击功能:

$('img').click(function(e){
e.preventDefault();//I use this to not direct myself to linked page for testing
var parent = $(e.target).parent('a');
console.log(parent.attr('href'));
})

答案 1 :(得分:2)

<强> Demo here

如果您在图像上有ID,则总是更容易。

  • 要检查您可以使用src <a>的图片if ($(this).parent('a').length) { 父母是否href

点击图片触发的功能内部:

  • 要从父<a>标记中获取$(this).parent('a').prop('href');值,您可以使用src
  • 要从图片中获取$(this).prop('src');值,请使用$('img').click(function () { $(this).preventDefault; if ($(this).parent('a').length) { var im = $(this).prop('src'); var aHref = $(this).parent('a').prop('href'); alert('First alert with imc src: '+im); alert('Second alert with link href: '+aHref); } });

整个代码:

{{1}}
相关问题