Bootstrap Dropdown selection是在*all*下拉菜单上设置选择

Bootstrap Dropdown selection is setting selection on *all* dropdowns

本文关键字:设置 选择 下拉菜单 all selection 是在 Bootstrap Dropdown      更新时间:2023-09-26

SO上有许多问题询问如何设置所选下拉列表的值,例如如何在引导按钮下拉标题中显示所选项目。这很有效,直到你在页面上添加第二个(或第三个…)下拉列表。然后发生的情况是,在下拉列表a上选择一个值将在下拉列表B和C上设置该值。。。

这是我的小提琴

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

当前选择器正在选择所有下拉菜单。。wheras所需要的是在所选的下拉按钮组中选择按钮,或者通过父对象遍历,这两种方法我都没能解决。

感谢您的帮助。

当您有$(".btn:first child")时,您正在搜索所有按钮

你需要相对于你当前的元素:

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

您需要在单击链接的行中选择btn。这是如何根据您的html 选择行

$(".dropdown-menu li a").click(function () {
    var item = $(this).text();   
    var current_row = $(this).parent().parent().parent().parent().parent();
    var current_btn = $(current_row).find(".btn:first-child");
 console.log($(current_row));     
    $(current_btn).text(item);
    $(current_btn).val(item);

});