gpt4 book ai didi

javascript - 如果其中包含图像标签,如何获取 anchor 标签的 href 值

转载 作者:行者123 更新时间:2023-11-29 16:15:10 24 4
gpt4 key购买 nike

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

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

以上工作正常,我可以获得图像 src。同样,我尝试仅在 anchor 标记中包含图像标记时才获取它的 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'));
})

关于javascript - 如果其中包含图像标签,如何获取 anchor 标签的 href 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com