[英]Populate Drop Down from Array
我正在嘗試填充數組列表字符串,以便隨后可以填充下拉列表。
我向它傳遞一個數組字符串,並像這樣設置我的數組列表:
var thirdParties = [{'7-Eleven', '114'},{'A Mart All Sports', '41'},{'A.J Coory Dental', '140'}];
然后,我試圖像這樣填充下拉列表:
if (id == 1) // Payment
{
//alert('Payment');
$('#SourceEntityId').empty();
$.each(accounts, function (val, text) {
$('#SourceEntityId').append($('<option></option>').val(val).html(text));
});
$('#DestinationEntityId').empty();
$.each(thirdParties, function (val, text) {
$('#DestinationEntityId').append($('<option></option>').val(val).html(text));
});
}
if (id == 2) // deposit
{
//alert('Deposit');
$('#SourceEntityId').empty();
$.each(thirdParties, function (val, text) {
$('#SourceEntityId').append($('<option></option>').val(val).html(text));
});
$('#DestinationEntityId').empty();
$.each(accounts, function (val, text) {
$('#DestinationEntityId').append($('<option></option>').val(val).html(text));
});
}
但是,下拉列表中沒有項目到達。 我在做什么,可能嗎?
您數組中的對象錯誤。
var thirdParties = [{
text: '7-Eleven',
value: '114'
}, {
text: 'A Mart All Sports',
value: '41'
}, {
text: 'A.J Coory Dental',
value: '140'
}];
$('#SourceEntityId').empty();
$.each(thirdParties, function () {
console.log(this);
var thirdParty = this;
$('#SourceEntityId').append($('<option></option>')
.val(thirdParty.value).html(thirdParty.text));
});
或另一種方式- 演示
var thirdParties = [['7-Eleven','114'],['A Mart All Sports','41'],['A.J Coory Dental','140']];
$('#SourceEntityId').empty();
$.each(thirdParties, function () {
var thirdParty = this;
console.log(thirdParty[1]);
$('#SourceEntityId').append($('<option></option>')
.val(thirdParty[1]).html(thirdParty[0]));
});
您在這里有兩個問題:
1.您的數組無效:
[{'7-Eleven', '114'},{'A Mart All Sports', '41'},{'A.J Coory Dental', '140'}];
您這里擁有的是一個包含無效對象的數組。
如果您想要一個數組數組,它應該看起來像這樣:
[['7-Eleven', '114'],['A Mart All Sports', '41'],['A.J Coory Dental', '140']];
如果您想要有效的對象數組,則需要提供鍵屬性,如下所示:
[{text:'7-Eleven', value:'114'},{text:'A Mart All Sports', value:'41'},{text:'A.J Coory Dental', value:'140'}];
2.jQuery每個的回調不包含 val\\text
但 index\\object
:
$.each(accounts, function (idx, obj) {});
因此,如果我們使用有效數組,則:
var arr = [{text:'7-Eleven', value:'114'},{text:'A Mart All Sports', value:'41'},{text:'A.J Coory Dental', value:'140'}];
$.each(arr, function (idx, obj) {
$('#SourceEntityId').append($('<option></option>').val(obj.value).html(obj.text));
});
這是小提琴 。
當您執行.html()時,該元素將清空並輸入變量。 您可能想使用.append()...
基本上,每次通過該循環運行時,都會重置容器。
另一件事是,您可以動態創建一個無序列表,然后以這種方式附加該列表,並且僅使用數據標簽來保存值。 它將為您提供更多空間來播放樣式和動畫。
var list_container = $("<ul/>").addClass ('list');
$('whatever container you decide this is going into').append(list_container);
$.each(thirdparties, function (index){
var li = $("<li/>").addClass('classname').attr('data-value',thirdparties[index].value);
$('.list').append(li);
$('li[data-value="'+thirdparties[index].value+'"]).html(thirdparties [index].text);
});
那只是我快速從手機上摘下的東西。 我將其插入jsfiddle並嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.