在Bootstrap Drop Down中设置默认值 [英] Setting Default Value in Bootstrap Drop Down
问题描述
我正在使用Bootstrap构建应用程序。在这个应用程序中,我有一个控件,可以转换英制和公制值之间的值。为实现此目的,我目前有以下内容:
I am building an app with Bootstrap. In this app, I have a control that converts a value between imperial and metric values. To accomplish this, I currently have the following:
<div class="input-group">
<input type="text" class="form-control">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Action <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a href="#" data-type="lb">Pounds</a></li>
<li><a href="#" data-type="kg">Kilograms</a></li>
</ul>
</div>
<input id="theValue" type="hidden" data-start-type="kg" />
</div>
当控件 theValue
元素填充自服务器,它将是lb或kg。我想这样做,以便在页面最初加载时,所选菜单选项基于 theValue
的值。换句话说,我不希望看到文本动作。相反,我需要在视图加载时选择Pounds或Kilograms。
When the control theValue
element is populated from the server, it will either be "lb" or "kg". I want to make it so that the selected menu option is based on the value of theValue
when the page initially loads. In other words, I do not want to see the text "Action". Instead, I need to select either Pounds or Kilograms when the view loads.
如何从jQuery执行此操作?
How do I do this from jQuery?
推荐答案
使用jQuery,您可以选择 theValue
元素,访问其 data-start-type
属性,找到具有相同数据类型
属性的 a
元素,然后使用它 text
设置按钮文本的值。你需要一种独特的方法来识别jQuery中的选择按钮,所以给它一个 id
;我用过actionButton。
Using jQuery, you would select the theValue
element, access its data-start-type
attribute, find the a
element with the same data-type
attribute, and then use its text
value to set the text of the button. You'll want a unique way to identify the button for selection in jQuery, so give it an id
; I used "actionButton".
$(document).ready(function(){
var data_start_type = $('#theValue').attr('data-start-type');
var $data_type_elem = $('[data-type='+data_start_type+']');
$('#actionButton').text($data_type_elem.text());
});
这是一个jsFiddle: http://jsfiddle.net/7g9k2dwx/
Here's a jsFiddle: http://jsfiddle.net/7g9k2dwx/
这篇关于在Bootstrap Drop Down中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!