gpt4 book ai didi

javascript - Bootstrap 多个下拉菜单更改相应的按钮文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:51 24 4
gpt4 key购买 nike

我有一个包含多个下拉菜单的页面,如下所示:

<div class="btn-group">
<button class="btn">Please Select From List</button>
<button class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
<li><a tabindex="-1" href="#">Item I</a></li>
<li><a tabindex="-1" href="#">Item II</a></li>
<li><a tabindex="-1" href="#">Item III</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="#">Other</a></li>
</ul>
</div>

我想将按钮文本更改为选定的元素值。我找到了这个线程:How to Display Selected Item in Bootstrap Button Dropdown Title ,它解释了如何检索所选元素的文本/值并更改按钮的文本,但是当页面上有更多下拉菜单时会出现问题,以下脚本会更改页面上所有按钮的标签:

$(function(){    
$(".dropdown-menu li a").click(function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});

如何修改让它只改变对应的下拉菜单按钮?作为附带问题:是否真的没有简单的方法来获得 <select>喜欢在 bootstrap 中开箱即用的下拉菜单行为?

最佳答案

您需要为您的 jQuery 选择器添加特殊性。目前,您正在选择具有 .btn 类的所有 元素,这些元素是其父元素的第一个子元素。您要做的是获取当前元素的父 .btn-group,然后在其中找到 .btn:first-child。您可以按如下方式执行此操作:

$(function(){    
$(".dropdown-menu li a").click(function(){
$(this).closest('.btn-group').find(".btn:first-child").text($(this).text());
$(this).closest('.btn-group').find(".btn:first-child").val($(this).text());
});
});

关于javascript - Bootstrap 多个下拉菜单更改相应的按钮文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com