将数组解析为SELECT OPTIONS。

15 浏览
0 Comments

将数组解析为SELECT OPTIONS。

这个问题已经有了答案

使用jQuery从Javascript对象中添加选项到选择框的最佳方法是什么?

我有一个像这样的数组:

["News & Politics", "Personal Journals", "Society & Culture", "Technology", "Arts", "Natural Sciences", "Business", "Comedy", "History", "Tech News", "TV & Film", "Design", "Performing Arts", "Education", "Christianity", "Investing", "Sports & Recreation", "Professional", "Social Sciences", "Automotive", "Science & Medicine", "Management & Marketing", "Sexuality", "Philosophy", "Self-Help", "Literature", "Buddhism", "Places & Travel", "Music", "Language Courses", "Careers", "Food", "Kids & Family", "National"]

我需要将这些值“推”到一个 select 中,其中数组中的每个项目都是它自己的 option

我该如何实现这一点?

该数组存储为变量 all_cat_unique,但(当然)以下内容不起作用。它只是将整个数组多次附加到选择框中。

$.each(obj.entry, function(i, data) {
    $('#all-categories').append(''+all_cat_unique+'');
});

谢谢。

admin 更改状态以发布 2023年5月21日
0
0 Comments
var all_cat_unique = ["News & Politics", "Personal Journals", "Society & Culture", "Technology", "Arts", "Natural Sciences", "Business", "Comedy", "History", "Tech News", "TV & Film", "Design", "Performing Arts", "Education", "Christianity", "Investing", "Sports & Recreation", "Professional", "Social Sciences", "Automotive", "Science & Medicine", "Management & Marketing", "Sexuality", "Philosophy", "Self-Help", "Literature", "Buddhism", "Places & Travel", "Music", "Language Courses", "Careers", "Food", "Kids & Family", "National"];
$.each(all_cat_unique, function(i, data) {
    $('#all-categories').append('');
});
/*get value selected*/
$("#all-categories").on("change", function() {
    alert("Selected: " + all_cat_unique[this.value]);
});



这段文本其中包含了两个嵌套的

标签和两个加粗的标签,整个段落看起来像是一个列表或者一段特定的格式化文本。但具体的含义我无法确定,因为这段文本断开了上下文。

0
0 Comments

给定的数组:

var all_cat_unique = ["News & Politics", "Personal Journals", "Society & Culture", "Technology", "Arts", "Natural Sciences", "Business", "Comedy", "History", "Tech News", "TV & Film", "Design", "Performing Arts", "Education", "Christianity", "Investing", "Sports & Recreation", "Professional", "Social Sciences", "Automotive", "Science & Medicine", "Management & Marketing", "Sexuality", "Philosophy", "Self-Help", "Literature", "Buddhism", "Places & Travel", "Music", "Language Courses", "Careers", "Food", "Kids & Family", "National"];

HTML选择框:


您可以使用以下代码将数组中的选项动态附加到选择框中:

for(var i = 0; i < all_cat_unique.length; i++)
$('#all-categories').append( $("").attr("value",all_cat_unique[i]).text(all_cat_unique[i]) );

这是一个可工作的jsfiddle,使用您给出的数组。 希望能有所帮助。

0