我使用BootstrapCSS并创建一个下拉菜单:
<div class="btn-group btn-group-sm">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" id="modal-button-operators" type="button" data-toggle="dropdown" data-target="#">Operator
<span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-operators" id="operator_list" style="height: auto; max-height: 200px; overflow-x: hidden;">
<li><a href="#" id="=">=</a></li>
<li><a href="#" id="<>"><></a></li>
<li><a href="#" id=">">></a></li>
<li><a href="#" id="<"><</a></li>
<li><a href="#" id=">=">>=</a></li>
<li><a href="#" id="<="><=</a></li>
<li role="separator" class="divider"></li>
<li><a href="#" id=" LIKE ">LIKE</a></li>
<li><a href="#" id=" BETWEEN ">BETWEEN</a></li>
</ul>
</div>
</div>
<div class="input-group-btn" id="button_query">
<a href="#" id= 'query_part' class="btn btn-primary btn-mg" data-toggle="modal" data-target="#myModal" title="Help" ><span class="glyphicon glyphicon-plus"></span></a>
</div>
稍后,在按钮单击时,我想获取所选值的ID并将其存储在变量中。这就是我的工作:
$(document.body).on("click", "#button_query",function(e) {
operator_list = $("#operator_list li a").attr('id');
});
但是这总是给我下拉列表的第一个选项的ID。 如何在下拉菜单中获取所选值的ID?
答案 0 :(得分:1)
您可以考虑在单击特定元素时添加CSS类,可以在按下按钮时使用该类来识别它:
// When an element from your list is clicked, set it as "selected"
$("#operator_list li:not(.divider)").click(function(){
// Ensure only the current one is selected
$("#operator_list li:not(.divider)").removeClass('selected');
$(this).addClass('selected');
});
然后通过以下方式访问所选的一个:
// Find the selected element and grab its id attribute
operator_list = $("#operator_list li.selected a").attr('id');
示例强>
你可以see a working example of this here并在下面演示: