我正在尝试让我的BS4下拉菜单在下拉切换按钮(即.dropdown-toggle
)中显示用户选择的值
这个问题以前已经被问过了,,但由于它使用了BS3框架,所以有点过时了。它也没有提供一个多次使用dropdown的方法。
我的在这里显示了我目前面临的问题,我是如何调整前面链接的解决方案的。
BS4下拉
<div class="btn-group">
<button class="btn btn-sm dropdown-toggle px-0 mr-3" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Sort by:
</button>
<div class="dropdown-menu">
<a class="dropdown-item active" href="#">Most Recent</a>
<a class="dropdown-item" href="#">Popular</a>
<a class="dropdown-item" href="#">Trending</a>
<a class="dropdown-item" href="#">Acending</a>
<a class="dropdown-item" href="#">Decending</a>
</div>
</div>
我的Jquery尝试
// Find all drop downs and check their classes.
$(".dropdown-menu a").click(function() {
// Find the dropdown toggle and append the text.
$(".dropdown-toggle:first-child").append($(this).text());
});
The question:
如何才能在页面上的所有下拉列表都不受影响的情况下达到预期的效果?此外,当选择一个新值时,我还需要删除附加的文本。
我追求的结果:button value = 'Sort by: Most Recent'
发布于 2019-07-10 03:07:53
经过多次测试,我最终使用以下代码达到了目标。感谢@Vinee提供的指导。
您可以通过;JSFiddle ;查看工作示例。
我已经对我的代码进行了注释,希望它能让任何使用它的人更容易理解。
这就是对我有效的方法。
$("document").ready(function() {
// The timeout is to wait the click, so the elements can render correctly.
setTimeout(function() {
// Trigger the active class on DOM Ready...
$('.btn-group').find('.active').trigger('click');
}, 10);
});
// On dropdown child click do...
$(".dropdown-menu a").click(function() {
// Remove any existing 'active' classes...
$(this).closest('.btn-group').find(".dropdown-menu a").removeClass('active');
// Add 'active' class to clicked element...
$(this).addClass('active');
// Remove any previous '<span class="appended">'
// This is needed so the values reset when a new option is clicked...
$(this).closest('.btn-group').find('.appended').remove();
// Add a new '<span class="appended">' element -
// and fill it with the clicked elements text
$(this).closest('.btn-group').find('button').append('<span class="appended">' + $(this).text() + '</span>');
});
希望这能对外面的人有所帮助。这对我来说很麻烦..。xD
问候你,-B。
发布于 2019-07-09 20:35:13
尝尝这个
$(".dropdown-menu a").click(function() {
//this one is add and remove active class
$(this).closest('.btn-group').find(".dropdown-menu a").removeClass('active');
$(this).addClass('active');
//this one is for append text in button tag
$(this).closest('.btn-group').find('button').append($(this).text())
});
});
发布于 2021-02-16 19:30:26
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<title>Lorem Ipsum Dolor </title>
https://stackoverflow.com/questions/56952354
复制相似问题