我尝试用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>
怎么做?哪个选择器更好?有什么想法吗?
发布于 2013-07-09 07:11:51
$('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'));
})
发布于 2013-07-09 07:41:17
如果你在图像上有一个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);
}
});
https://stackoverflow.com/questions/17542113
复制相似问题