繁体   English   中英

如果锚标签中包含图像标签,如何获取href值

[英]How to get href value of anchor tag if it has image tag in it

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

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

以上工作正常,我可以得到图像src。 同样,我尝试仅在锚标签中具有图像标签的情况下才获取锚标签的href值,否则不应这样做。以下是其中包含图像标签的示例。

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

怎么做?选择器更好些?有什么主意吗?

$('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'));
})

在这里演示

如果您在图像上有一个id,总是比较容易。

  • 要检查图像src 是否具有作为<a>父对象,可以使用: if ($(this).parent('a').length) {

在点击图片触发的函数内部:

  • 要从作为<a>标记的父项获取href值,可以使用: $(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);
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM