jQuery函数,一个用于在单击时显示下拉列表,另一个用于从下拉列表中获取所选项目

jQuery functions, one to display dropdown on click and another to get selected item from dropdown

本文关键字:用于 下拉列表 另一个 获取 项目 选项 显示 单击 函数 jQuery 一个      更新时间:2023-09-26

我有一个无序的列表(下面是HTML,下面是Javascript代码)。

第一个函数"display_dropdown_multiple"适用于我第二个函数"get_selected_owner"。

从下拉菜单中进行选择后。我希望第二个函数返回"选定的值"。如有任何帮助,我们将不胜感激。

function display_dropdown_multiple(event) {
    $(".dropdown-menu").on('click', 'li a', function(){
      $(this).parents(".btn-group").find('.btn').text($(this).text());
      $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
       });
});
function get_selected_owner() {
    return $('#owner').find('option:selected').val();
    });        
});
<div class="btn-group">
    <button type="button" class="btn btn-success dropdown-toggle" id="owner" data-toggle="dropdown">
      Owner <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="owner-dropdown-menu">
      <li role="presentation" class="dropdown-header">major</li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#" id="owner"><input type="hidden" onclick='display_dropdown_multiple(event)' id="ownerId" name="ownerId" value="Owner 1" >Owner 1</a></li>
      <li class="divider"></li>
      <li role="presentation" class="dropdown-header">minor</li>
      <li><a href="#" id="owner"><input type="hidden" onclick='display_dropdown_multiple(event)' id="ownerId" name="ownerId" value="Owner 2" >Owner 2</a></li>
      <li><a href="#" id="owner"><input type="hidden" onclick='display_dropdown_multiple(event)' id="ownerId" name="ownerId" value="Owner 3" >Owner 3</a></li>
    </ul>
</div>

  1. ID必须是唯一的
  2. 没有您要针对的<option>

解决方案

构造一个<select>,其中包含您打算用于唯一id的选项,然后您的代码就可以正常工作了。