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

Javascript 如果锚定标记中有图像标记,如何获取锚定标记的href值,javascript,jquery,jquery-selectors,Javascript,Jquery,Jquery Selectors,我尝试使用jquery获取图像src,下面是代码 jQuery("img").click(function() { var im = $(this).attr('src'); alert(im); return false; }); 以上工作良好,我可以得到图像src。同样地,我尝试仅在锚定标记中包含图像标记时获取锚定标记的href值,否则不应该获取锚定标记的href值。下面是一个包含图像标记的示例 <a href="some.something"><

我尝试使用jquery获取图像src,下面是代码

jQuery("img").click(function() {
    var im = $(this).attr('src'); 
    alert(im);
    return false;
});
以上工作良好,我可以得到图像src。同样地,我尝试仅在锚定标记中包含图像标记时获取锚定标记的href值,否则不应该获取锚定标记的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,那就容易多了

  • 要检查image
    src
    是否具有属于
    的父级,可以使用:
    if($(this).parent('a').length){
在通过单击图像触发的功能内:

  • 要从父级获取
    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);
}
});

单击事件时可以访问它吗?@raam86i像这样尝试
jQuery('img')。父('a')。单击(函数(){});
谢谢兄弟。为什么是concole.log?如果你有时间解释:)我发现这个函数更适合调试,因为它有时提供更多的信息,而且远远不够annoying@raj,谢谢!刚刚用href更新了答案。您也可以在此处查看: