我想插入option
带有文本和读取值的标签 xml
标签。
这里我想插入<option value> Text</option>
就像下面这样:
<强> <option value[from each xml col1]> Text [from each xml col2] </option>
这是代码:
var xml = ' <row id="1_2"> <col1>46.0</col1> <col2>Acting Allowance</col2> </row> <row > <col1>A1</col1> <col2>Allowance for 65 years plus</col2></row>',
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$xml.find('col2').each(function () {
var option = $(this).text(), //i want to take text from each col2 as option text
value = $(this).attr('value'); //i want to take text from each col1 as option value
$("#selectID").append("<option value='" + value + "'>" + option + "</option>");
});
<select id="selectID"></select>
请告诉我更多信息。谢谢。
最佳答案
您的XML
无效。您必须插入任何根节点(我刚刚用 <root>
节点包装了 xml。
var xml = '<root><row id="1_2"><col1>46.0</col1><col2>Acting Allowance</col2></row><row><col1>A1</col1><col2>Allowance for 65 years plus</col2></row></root>',
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$xml.find('row').each(function() {
var row = $(this),
option = row.find('col2').text(), //i want to take text from each col2 as option text
value = row.find('col1').text(); //i want to take text from each col1 as option value
$("#selectID").append("<option value='" + value + "'>" + option + "</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectID"></select>
关于javascript - 如何在 html 选项文本和值中插入 xml 文本和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34479930/