[英]How to display dropdown menu items inside the dropdown using javascript?
以下是我的html:
<div class="row">
<div class="col-lg-11">
<ul class="list-unstyled" id="slider">
</ul>
</div>
</div>
以下是我的JavaScript:
var locationbegin="<div class='form-group'><label>Location</label><select
class='form-control' id='location'><option>test</option>";
$("#slider").append(locationbegin);
var locationoptions = "<option>tester</option>";
$("#slider").append(locationoptions);
var locationend="</select> </div>";
$("#slider").append(locationend);
以下是輸出:
問題是測試儀出現在位置下拉列表中。 我不確定我要去哪里。 您也可以使用http://rendera.herokuapp.com/呈現代碼。
編輯:javascript分離的原因是由於代碼中之間存在其他一些javascript代碼。
您使用不正確的HTML會出錯。 您必須關閉標簽,否則瀏覽器在計算出標簽時應為您執行此操作。 append
首先將您的HTML轉換為NodeList(這將導致select
和div
關閉),然后將i附加到滑塊。 現在,如果將其他options
附加到該HTML結構上,則可以將thos有效地附加在封閉的div
后面。
您應該保留對select
的引用,以便在需要時可以添加更多的optinos:
a)創建周圍的標記:
var myFormField = $('<div class="form-group"><label>Location</label><select class="form-control" id="location"><option>test</option></select></div>')
b)找到select
並將其存儲到變量中:
var mySelect = myFormField.find('#location');
c)根據需要添加盡可能多的選項
mySelect.append('<option>Value 2</option>');
mySelect.append('<option>Value 3</option>');
mySelect.append('<option>Value 4</option>');
哦,這不是怎么回事。 如果您的HTML字符串中沒有.append
則會自動添加closing tags
。
因此,在第一次追加調用之后,您的html將變為:
<div class='form-group'>
<label>Location</label>
<select class='form-control' id='location'>
<option>test</option>
</select>
</div>
在此HTML之后將進行進一步的插入。
因此,請執行以下操作:
var locationbegin="<div class='form-group'><label>Location</label><select
class='form-control' id='location'><option>test</option>";
var locationoptions = "<option>tester</option>";
var locationend="</select> </div>";
$("#slider").append(locationbegin + locationoptions + locationend);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.