javascript - 获取父元素并找到按钮元素并替换它的文本

标签 javascript jquery

我有这个代码。

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相反。

Example Here

$('.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/

相关文章:

javascript - 加载内联 jQuery 脚本以及延迟和异步脚本

jquery multiple buttons to display same form 一键点击触发所有按钮的表单

javascript - jQuery jqGrid 中的事件之前排序

javascript - 三个js中网格的中间挤压

javascript - 将位置绝对元素对齐到相对元素的末尾

javascript - 变量不会更改类内的属性

javascript - 使用 CasperJS 正确地遍历数组和打开页面

php - 来自 PHP 的 jQuery 的 AJAX 响应有困难

javascript - 如何重命名 Meteor 包?

javascript - webstorm 无法识别“require”关键字