[英]Set Default Drop Down Value in Bootstrap
我是 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>
我已經嘗試了一些類似問題的建議,但這些在我的情況下不起作用。 第一個是:
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”。 我發現這個建議我把它放在我的 JS 代碼下面,但它沒有設置任何默認值。
$('#country_select li a')[2].click();
有人可以指出我該如何解決這個問題嗎?
您希望能夠使用列表來執行此操作,因為下拉菜單沒有列表。
嘗試這個:
<select>
<option>.....</option>
<option selected="selected">Select a language</option>
<option>.....</option>
<option>.....</option>
<option>.....</option>
</select>
您確定您正確放置了代碼嗎?
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);
編輯:這是一個演示。 如果您在底部打開控制台,您將看到默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.