使用bootstrap 3的下拉组件,我需要获得对选择以及所选文本的引用

时间:2014-07-23 06:38:36

标签: twitter-bootstrap-3

我使用下拉列表选择一个选项,需要使用选择来控制后续处理。

<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" >
    Select Action
    <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation" class="dropdown-header">Handling Documents</li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Create Document from Form</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Create New Folder</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Rename Folder</a></li>

</ul>
</div>

我在点击功能

中获得所选文字
$('.dropdown-menu li').click(function(e){
e.preventDefault();
var selected = $(this).text();
console.log('action '+selected); 
$('#main_action_text').text(selected);
});

我想在我的javascript中使用所选操作行的参考编号,以避免测试“创建文档...”等。 如何最好地实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以使用数据属性:

<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
  <li role="presentation" class="dropdown-header">Handling Documents</li>
  <li role="presentation" data-action="1"><a role="menuitem" tabindex="-1" href="#">Create Document from Form</a></li>
  <li role="presentation" data-action="2"><a role="menuitem" tabindex="-1" href="#">Create New Folder</a></li>
  <li role="presentation" data-action="3"><a role="menuitem" tabindex="-1" href="#">Rename Folder</a></li>
</ul>

使用jQuery:

$('.dropdown-menu li').click(function(e){
  e.preventDefault();
  var action = $(this).data('action');
  console.log('action : ' + action);
});