Javascript bootstrap 下拉菜单中的默认选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37503955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default selection in bootstrap dropdown
提问by Cybernetic
I am using a bootstrap dropdown, and need to have the first option as default. The following doesn't work.
我正在使用引导程序下拉菜单,并且需要将第一个选项作为默认值。以下不起作用。
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
CHOOSE FEATURE
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li selected="selected"><a>Feature 1</a></li>
<li><a>Feature 2</a></li>
<li><a>Feature 3</a></li>
<li><a>Feature 4</a></li>
<li><a>Feature 5</a></li>
<li><a>Feature 6</a></li>
</ul>
回答by Jason Graham
Unfortunately, I don't believe you'll be able to achieve this effect using a conventional bootstrap drop down menu.
不幸的是,我不相信您能够使用传统的引导下拉菜单实现这种效果。
Unlike a traditional HTML "select", a bootstrap drop down is typically used to group a series of links under a header. When you click a menu item, it doesn't become selected as such, rather an action is usually performed.
与传统的 HTML“选择”不同,引导下拉菜单通常用于将一系列链接分组到标题下。当您单击一个菜单项时,它不会被选中,而是通常会执行一个操作。
I'd advise just using a straightforward HTML select, but borrowing styles from the bootstrap CSS library so it looks consistent. Something along the lines of:
我建议只使用简单的 HTML 选择,但从引导 CSS 库中借用样式,使其看起来一致。类似的东西:
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
回答by Nitish Sahu
Try this:
尝试这个:
$(document).ready(function() {
$(".dropdown .dropdown-menu li a")[0].click();
});
This will always select your first li
这将始终选择您的第一个 li
回答by Charlie
The attribute "selected" only works in <select>
elements. Unfortunately it does not work in lists.
属性“selected”仅适用于<select>
元素。不幸的是,它在列表中不起作用。
I believe what you want is:
我相信你想要的是:
<select class="form-control" name="features">
<option value="" selected>Feature 1</option>
<option value="">Feature 2</option>
<option value="">Feature 3</option>
<option value="">Feature 4</option>
<option value="">Feature 5</option>
<option value="">Feature 6</option>
</select>