使用jQuery在下拉列表中预选唯一项

使用jQuery在下拉列表中预选唯一项,jquery,twitter-bootstrap,Jquery,Twitter Bootstrap,在某些情况下,我的一些引导下拉控件中只有一个选项,因此我希望在这些情况下预先选择该值。几乎没有开创性 下拉列表位于引导中,并使用关联的ul作为值,如下所示 下拉列表定义为 <div class="btn-group postage"> <button type="button" class="form-control btn btn-default dropdown-toggle postDropDown" data-toggle="dropdown">

在某些情况下,我的一些引导下拉控件中只有一个选项,因此我希望在这些情况下预先选择该值。几乎没有开创性

下拉列表位于引导中,并使用关联的ul作为值,如下所示

下拉列表定义为

<div class="btn-group postage">
    <button type="button" class="form-control btn btn-default dropdown-toggle postDropDown" data-toggle="dropdown">
         select...
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu" id="postList">
        <li id="foobar">
            <a href="javascript:void(0)" class="postitemselector">Why do I have to select when there is only one item in the list?</a>
        </li>
    </ul>                    
</div>

如何通过jQuery预先选择列表中的项目?(注意,我不想更改下拉列表的标记)

我可以通过一种方式触发手动单击事件

$(".dropdown-menu li a").click(function () {
   //Add back the pesky caret which otherwise gets removed on selection.
   $(this).closest(".btn-group").find(".btn:first-child").html($(this).html() + '<span class="caret"></span>');
});

$(document).ready(function () {
    //need to do this after teh click handler is added
    $('#postList li:first a').click();
});
$(“.下拉菜单a”)。单击(函数(){
//添加回讨厌的插入符号,否则在选择时会被删除。
$(this).closest(“.btn group”).find(“.btn:first child”).html($(this.html()+”);
});
$(文档).ready(函数(){
//需要在添加单击处理程序后执行此操作
$('#postList li:first a')。单击();
});

演示:

Super。谢谢阿伦:)
$(".dropdown-menu li a").click(function () {
   //Add back the pesky caret which otherwise gets removed on selection.
   $(this).closest(".btn-group").find(".btn:first-child").html($(this).html() + '<span class="caret"></span>');
});

$(document).ready(function () {
    //need to do this after teh click handler is added
    $('#postList li:first a').click();
});