在Bootstrap中设置默认下拉值

ddrv8njm  于 2022-12-16  发布在  Bootstrap
关注(0)|答案(2)|浏览(250)

我是新的JS和想设置一个默认值时,页面加载。我的HTML:

<!DOCTYPE html>
    <html>
      <head>
        <script src="js/jquery.min.js"></script>
        <script src="shared/shiny.js" type="text/javascript"></script>
        <script src="css/bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="css/bootstrap-3.3.6-dist/css/bootstrap.min.css">
        <script src="js/app.js" type="text/javascript"></script>
      </head>
      <body>
       <div class="dropdown" id="country_select">
        <button class="btn btn-default dropdown-toggle" type="button"
          data-toggle="dropdown">Country<span class="caret"></span></button>
            <ul class="dropdown-menu">
             <li><a href="#" country-code="C1">Country1</a></li>
             <li><a href="#" country-code="C2">Country2</a></li>
             <li><a href="#" country-code="C3">Country3</a></li>
            </ul>
       </div>
     </body>

我试过类似问题中的一些建议,但这些建议在我的情况下不起作用。first的建议是:

var main = function(){
        var data_start_type = "C1";
        var $data_type_elem = $('[country-code='+data_start_type+']');
        $('#country_select li a').text($data_type_elem.text());

    $("#country_select li a").on("click", function () {
            var country_selected=$(this).text();
            Shiny.onInputChange('this_country', country_selected);  //send selected data to the server script
    });
};

    $(document).ready(main);

上面的代码将下拉列表的所有选项设置为“Country1”。我发现this建议我将其放在JS代码下面,但它没有设置任何默认值。

$('#country_select li a')[2].click();

有人能告诉我怎么修吗?

nlejzf6q

nlejzf6q1#

您希望能够使用列表来完成此操作,因为列表不是为下拉菜单创建的。
试试这个:

<select>
<option>.....</option>
<option selected="selected">Select a language</option>
<option>.....</option>
<option>.....</option>
<option>.....</option>
</select>
fumotvh3

fumotvh32#

您确定您的代码放置正确吗?

var main = function(){
    var $menu_items = $("#country_select li a");

    $menu_items.on("click", function () {
        Shiny.onInputChange('this_country', $(this).text());
    });
    $menu_items[0].click(); // 0 for Country1, 1 for Country2, etc
};
$(document).ready(main);

**编辑:**这里有一个demo。如果你打开底部的控制台,你会看到默认值。

相关问题