2015-04-21 52 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()); 
});