2015-04-21 45 views
3

我有這段代碼。獲取父元素並找到按鈕元素並替換它的文本

HTML

<div class="has_dropdown"> 
    <button>Select branch</button> 
    <ul class="dropdownmenu"> 
     <li><a href="#">Branch 1</li> 
     <li><a href="#">Branch 2</li> 
     <li><a href="#">Branch 3</li> 
    </ul> 
</div> 

這jQuery腳本

$('.dropdownmenu li a').click(function(){ 
    //go to the .has_dropdown which is the parent container and find button element within it and then replace the text of it with the current click anchor element text. 
    $(this).parent('.has_dropdown').find('button').text($(this).text()); 
}); 

,你可以從腳本代碼中看到的,它會去父元素.has_dropdown然後查找內部的按鈕元素然後用當前單擊的元素(.dropdownmenu li a)的文本替換按鈕的元素文本,但可惜不起作用。任何幫助線索,想法,建議和建議,使這項工作?

+0

變化'.parent'到'.closest' –

回答

4

這是因爲元素.has_dropdown不是<a>元素的直接父級。您需要改用.closest() method

Example Here

$('.dropdownmenu li a').click(function(){ 
    $(this).closest('.has_dropdown').find('button').text($(this).text()); 
}); 

.parent() method橫穿至直接父而.closest method通過其祖先穿越了。

+0

謝謝!作品像魅力:) –

0

.parent()只檢索您的html中最接近的父元素,即<li>。如果你喜歡去的按鈕,只要使用parent()你可以這樣做:

$('.dropdownmenu li a').click(function(){ 
    $(this).parent().parent().prev().text($(this).text()); 
});