我有这个代码。
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)但遗憾的是没有工作。有任何帮助线索、想法、建议、推荐来完成这项工作吗?
最佳答案
因为元素.has_dropdown
不是 <a>
的直接父级元素。您需要使用 .closest()
method相反。
$('.dropdownmenu li a').click(function(){
$(this).closest('.has_dropdown').find('button').text($(this).text());
});
.parent()
method遍历到直接父级,而 .closest
method遍历其祖先。
关于javascript - 获取父元素并找到按钮元素并替换它的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762419/