如何使用jQuery从字符串数组生成UL Li列表?
我有像这样的字符串数组
“美国”,“加拿大”,“阿根廷”,“亚美尼亚”,“阿鲁巴”, “澳大利亚”,“奥地利”,“阿塞拜疆”,“巴哈马”,“孟加拉国”, “白俄罗斯”,“比利时” **等。
我想从字符串数组创建动态列表,如下所示:-
United States
Canada
....
.....
如何使用jQuery?
7个解决方案
85 votes
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
var li = $('
')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('')
.addClass('ui-all')
.text(countries[i])
.appendTo(li);
});
Sai Sherlekar answered -08-10T19:13:28Z
13 votes
使用数组的join方法甚至更好的方法
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var list = '
' + countries.join('') + '';
SM Farhad Ali answered -08-10T19:13:47Z
9 votes
使用ES6,您可以编写以下代码(跳过一些HTML属性以避免不必要的干扰):
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('
', {class: "mylist"}).append(
countries.map(country =>
$("
").append($("").text(country))
)
);
tokland answered -08-10T19:14:07Z
5 votes
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
var li = $('
')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var a = $('')
.addClass('ui-all')
.text( this )
.appendTo(li);
});
Mike Thomsen answered -08-10T19:14:23Z
4 votes
function aa()
{
var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
var ObjUl = $('
for (i = 0; i < YourArray.length; i++)
{
var Objli = $('
');
var Obja = $('');
ObjUl.addClass("ui-menu-item");
ObjUl.attr("role", "menuitem");
Obja.addClass("ui-all");
Obja.attr("tabindex", "-1");
Obja.text(YourArray[i]);
Objli.append(Obja);
ObjUl.append(Objli);
}
$('.DivSai').append(ObjUl);
}
Sai Sherlekar answered -08-10T19:14:38Z
2 votes
Abhishek Bhalani的其他变化:您可以使用Array.map()代替$ .each()
var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
var li = $('
')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
$('')
.appendTo(li);
});
Pasha Oleynik answered -08-10T19:14:58Z
0 votes
也可以不使用jQuery! :)
Josh Withee answered -08-10T19:15:18Z