2013-02-19 32 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')