2014-09-30 54 views
-1
<div class="ptp-item-container"> 
    <div class="plan">Text I want!</div> 
    <div class="price">200</div> 
    <div class="bullet-item">some other text</div> 
    <div class="cta"> <a class="button" href="javascript:getText()">Go!</a> 
    </div> 
</div> 

從按鈕我嘗試這樣做:如何到達此元素?

function getText(){ 
    alert($(this).parent().parent().children().text()); 
} 

這並沒有真正的工作,我知道有一種方法!這次使用$(this)是很重要的。

編輯:這是整個的Javascript:

<script> 
    jQuery(document).ready(function($) { 
     $(".ptp-button").attr("href", "javascript:getText()"); 
    }); 
     function getText(){ 
      alert($(this).closest('.ptp-item-container').find('.plan').text()); 
     } 
</script> 

但控制檯說: 「遺漏的類型錯誤:未定義是不是一個函數VM4092:1(匿名函數)」

不要我給$ (this)作爲javascript:getText($(this))的參數或類似的東西?

+1

爲什麼不使用'。對()'爲點擊處理程序,而不是有href調用js? – Huangism 2014-09-30 13:52:39

回答

3

你不應該javascript: HREF瞄準它。相反,使用.on()處理程序,這是處理JQuery上的點擊事件的正確方法。然後,你就可以使用this參考:通過父母

然後,已經回答了,而不是導航,使用.closest()功能:

$('.ptp-item-container').on('click', '.button', function() { 
    alert($(this).closest(".ptp-item-container").find(".plan").text()); 
}); 
+0

我認爲你的選擇器應該是「.ptp-item-container a.button」 – Heraldmonkey 2014-09-30 13:55:51

+0

@Heraldmonkey不,再看一遍。他們正在選擇它。更多關於他們選擇它的方式[** here **](http://api.jquery.com/on/) – Ruddy 2014-09-30 13:57:06

+0

是的@Heraldmonkey,但它的工作原理是一樣的。這只是確保錨點被包裝在「.ptp-item-container」元素中的一種方式。 – LcSalazar 2014-09-30 13:58:04

0

您可以使用.closest().find()組合:

alert($(this).closest(".ptp-item-container").find(".plan").text()); 

是值得花一些時間瀏覽the jQuery API documentation.

+2

對不起這裏正確的小提琴http://jsfiddle.net/u68vv1yu/1/'$(this)'不是指錨點 – Huangism 2014-09-30 13:56:09