我试着用 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/