2013-02-19 87 views
1

我想使用jQuery并点击()来抓取图像链接的URL,一旦点击它。这个html看起来像这样。使用jquery点击函数抓取图像链接的url

<div class="lp-element lp-pom-image" id="lp-pom-image-167" > 
<a href="http://url.com/page" target=""><img src="/image.jpg" alt=""></a> 
</div> 

到目前为止,我使用的JavaScript看起来像这样,但它并没有抓住点击图像链接的网址。该网址需要传递到变量this所在的位置。

jQuery(function() { 
jQuery("#lp-pom-image-167").click(function() { 
trackOutboundLink(this, 'AddToCart', 'Bottom CTA'); 
return false; 
}); 
}); 

如何将href网址与适当的基础URI相提并论?即。 “http://url.com/page”?

编辑:澄清了我试图拔出。

+1

'$(this).children(“a img”)。attr('src')'应该这样做。 – Supericy 2013-02-19 00:34:52

+2

''希望你不打算复制粘贴这个(任何)JS代码像这样一个200倍的所有'#lp-pom-image-NNN'元素....'' – 2013-02-19 00:36:55

+0

@Supericy jQuery' .prop'应该用来代替'.attr'。 – Mooseman 2013-02-19 00:40:31

回答

1

工作演示中,我会建议(虽然未经测试):

$('.lp-pom-image').click(function(e){ 
    e.preventDefault(); // stops the default action, 
         // without preventing propagation/bubbling 
    trackOutboundLink($(this).find('img').prop('src'), 'AddToCart', 'Bottom CTA'); 
}); 
+0

类似于我的例子,但你使用.attr()的.prop()instad。注意:从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()检索属性。 http://api.jquery.com/prop/ – 2013-02-19 00:49:10

+0

@Maksym:是的,我知道。但感谢您花时间指出这一点。我假定他想要完整的URL(因此'prop()')而不是检索可能在属性中的潜在的相对URL(用'attr()'得到的URL)。 – 2013-02-19 00:51:17

+0

这个工作,虽然我换了find('img')find('a')。谢谢! – incognito2 2013-02-19 01:07:18

0
jQuery(".lp-pom-image").click(function() { 
    console.log($("img", this).attr("src")); 
    return false; 
}); 

看到http://jsbin.com/ebicax/4/

0

使用下面的代码,而不是this,如果你想获得a网址:

$(this).find("a").attr('href') 

或此代码如果你想得到img src:

$(this).find("a img").attr('src')