[英]Jquery - Array manipulation from a select box
我正在根据类别创建标签建议功能。 因此,我有一个带有一系列类别的选择框,当我选择一个类别时,我想在列表中显示子类别(显然使用数组)。 这是我现在所拥有的:
<select id="categorySelect">
<option value="6">Animal</option> //the value here is the category id
<option value="12">Music</option>
</select>
<ul id="suggestedTags">
</ul>
我的JSON数组:
var tagsMakers= [
{ category: 'Animal', suggestedTags: [
{ name: 'cat'},
{ name: 'dog' },
{ name: 'rabbit'}
]},
{ category: 'Music', suggestedTags: [
{ name: 'rock' },
{ name: 'rap' }
]}
];
$("#categorySelect").change(function(){
});
我仍在学习数组操作,而且我不知道从哪里开始!
换句话说,逻辑是:
当选择一个类别时,我想在下面的li中显示该类别的所有建议标签。 我还希望能够选择多个类别,因此,如果同时选择两个类别,则希望同时显示两个建议的标签。
有人有时间帮助吗?
是的,首先将事件绑定到选择标签,然后基于该值显示列表。 还要删除JSON结构,并建立一个哈希值:
tagMakers = {'Animal': ['Cat','Dog','Rabbit'], 'Music': ['rock','rap']}
$("#categorySelect").change(function() {
$("#suggestedTags").empty();
$(this).find(":selected").each(function() {
var selected = $(this).text();
$.each(tagMakers[selected].function(i,n) {
$("#suggestedTags").append("<li>"+n+"</li>");
});
});
});
您的标记数组没有类别ID,因此在这里我将使用类别名称。 但是,作为一种好的做法,如果您将category ID放在Categories数组中,那就更好了。 更好的是,如果使用对象哈希而不是数组。
function getCategoryByName(name){
//search in array.
for(var i = 0, len = tagsMakers.length; i < len; i++)
{
if (tagsMakers[i].category === name)
{
// found.
return tagsMakers[i];
}
}
// do not exists
return;
}
$("#categorySelect").change(function(){
// get the selected value
var current = $(this).val(),
suggestedTags = $("#suggestedTags"),
category;
// we do not have the category id on 'tagsMakers', so
// we need the category name.
current = $("option[value="+current+"]", this).text();
//search in array.
category = getCategoryByName(current);
//populate the suggested tags
suggestedTags.empty()
$.each(category.suggestedTags, function(i, tag) {
$("<li>" + tag.name + "</li>").appendTo(suggestedTags);
});
});
jsFiddle: http : //jsfiddle.net/vcZnu/
编辑:如果您可以通过对象哈希(更好)来更改类别数组,那么您可以使用@CupidVogel提供的解决方案,否则可以使用此解决方案来解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.