从xml动态创建下拉列表 [英] create drop down dynamically from xml
问题描述
我今天遇到创建下拉列表的问题:
I have today problem with creating drop-down lists:
我有像这样的结构的xml文件:
I have xml file like with such structure like this:
<resultset>
<row>
<field name="iso3166_2">AF</field>
<field name="country">AFGHANISTAN</field>
<field name="fixed">1.000</field>
<field name="mobile">1.300</field>
</row>
<row>
<field name="iso3166_2">US</field>
<field name="country">ALASKA</field>
<field name="fixed">0.100</field>
<field name="mobile">0.100</field>
</row>
</resultset>
我想创建包含国家/地区名称的下拉列表(取自以下字段: < field name =country> ...< / field>
)。
And I would like to create drop-down list with country names in it (taken from those fields: <field name="country">...</field>
).
此外,从此下拉列表中选择国家/地区后,我想显示已修复
和<$的变量c $ c> mobile 来自相同的行
设置为此选择的 country
:
In addtion, after choosing country from this drop-down I would like to show variables from fixed
and mobile
from the same row
set as chosen country
in such span's:
< span id =mobile><! - 移动值 - >< / span>
和< span id =fixed><! - 固定值 - >< / span>
我希望很清楚我想要实现的目标,我试图通过类似问题的答案解决它:动态加载数据从xml到下拉框与jquery 但它不适合我(我做错了什么我想)。请帮忙!
I hope it is clear what I want to achieve, I was trying to solve it with answers from similiar question: dynamic load data from xml to drop down box with jquery but it's not working for me (I was doing something wrong I suppose). Please help!
推荐答案
这样的事情应该有效:
$.ajax({
url: 'img/test.xml',
dataType: 'xml', // Make sure it knows to treat it as XML
success: function(xml) {
var rows = xml.childNodes[0].getElementsByTagName("row"),
// This assumes your <select> has id of "countries"
$dropdown = $("#countries");
$(rows).each(function(index, row) {
var fields = row.getElementsByTagName("field"),
$option = $(document.createElement("option"));
$(fields).each(function(index, field) {
var name = field.getAttribute("name"),
// A special way to get the text contents of an XML node
value = $(field).contents()[0].wholeText;
// If it's the "country" field, just stick it in the option
if (name == "country") {
$option.text(value);
} else {
// If it's anything else, store it as extra data
$option.data(name, value);
}
});
$dropdown.append($option);
});
// Whenever you change which option is selected
$dropdown.change(function() {
$option = $dropdown.find(":selected");
// Fill in the spans using the extra data you saved
$("#fixed").text($option.data("fixed"));
$("#mobile").text($option.data("mobile"));
});
}
});
简而言之,如果您通过AJAX提取XML,请确保将其视为XML,然后您就可以对待它就像它的任何其他类型的文件(有一些警告)。很明显,这可以使用vanilla JavaScript完成,但我发现使用jQuery更容易。
In short, if you pull in your XML through AJAX, make sure it's treated as XML then you can treat it just like it's any other kind of document (with some caveats). Clearly this could be done with vanilla JavaScript but I find it easier to do with jQuery.
这篇关于从xml动态创建下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!