[英]How to get more data from json array when a value in option tag is selected jquery
I'm trying to display more info of the museum when a museum name is clicked fro the option dropdown box. 当尝试通过选项下拉框单击博物馆名称时,我试图显示有关该博物馆的更多信息。 I am getting my data from a json array. 我正在从json数组中获取数据。 I was able to populate the option box with the name of the museum but could not display more details. 我能够用博物馆的名称填充选项框,但无法显示更多详细信息。 Could anyone please help me with this. 谁能帮我这个忙。 I'm using jquery for this code. 我正在为此代码使用jquery。
function getMuseums() {
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo()\" />");
var info = $("<span>Select Museum: </span>")
$.get("museums.php",function(data,status) {
var response = '';
var json = $.parseJSON(data);
museums = json.museums;
$.each(museums, function (index, item) {
$('<option />').attr({"value" : index}).text(item.museum_name).appendTo(museumSelect);
/*response += "<option value='"+index+"'>" + item.museum_name + "</option>";
$("#museumlist").html(response);*/
});
$('#content').empty().append(info, museumSelect);
$("<div id=\"museumDetails\" />").appendTo("#MuseumDiv");
getMuseumInfo()
});
}
function getMuseumInfo() {
var museum_id = $("#museumlist").val();
selectedMuseumid = museum_id;
$("#MuseumDiv").empty().append("<div id=\"museumDetails\"/>");
var url = "museums.php?museum_id=" +escape(museum_id);
$.get(url,function(data,status) {
var json = $.parseJSON(data);
museums = json.museums;
var museum_name = museums.museum_name;
var museum_description = museums.museum_description;
var museumInfo = "<h3>" + museum_name + "</h3><p>" + museum_description + "</p>";
$("#museumDetails").empty().append(museumInfo);
});
}
You can pass option value to your function as a parameter getMuseumInfo(this.value)
: 您可以将选项值作为参数getMuseumInfo(this.value)
传递给函数:
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo(this.value)\" />");
And than you can use iterate through museums and check if index is the same as option value, and then print only properties for that item. 然后,您可以遍历博物馆,检查索引是否与选项值相同,然后仅打印该项目的属性。
$.each(museums, function(index, item) {
if (index == id) {
var museumInfo = "<h3>" + item.museum_name + "</h3><p>" + item.museum_description + "</p>";
$("#MuseumDiv").empty().append(museumInfo);
}
});
But better check working code (also turn on console in app): codePen 但是最好检查工作代码(也可以在应用程序中打开控制台): codePen
NOTE: I make example of request to create JSON data. 注意:我以创建JSON数据的请求为例。 I make get request to url: https://api.myjson.com/bins/58j10 我向网址发出请求: https : //api.myjson.com/bins/58j10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.