我从API
电话中获取了这些数据:
rfc2606
我想显示这些数据以选择选项元素,所以我在我的AJAX脚本文件中有这行代码:
$.each($(value.routes), function(index, route){
$('.searchable-select').append('\
<option value="'+route+'"> From: '+route+'</option>\
');
});
如何将选项值设置为1和2以及字符串(“From:...”)作为此对象的文本?
答案 0 :(得分:1)
如果要迭代routes对象,可以使用$ .each的jquery。
代码看起来像这样。
var routes = {
1: "From Davao Del Sur (Phillipines) ...",
2: "From Soccsksargen (Phillipines)"
}
var select = '<select>';
$.each(routes, function(index, route) {
select += '<option value="'+ index +'">'+ route +'</option>';
})
select += '</select>';
$('#demo').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>
答案 1 :(得分:0)
如果我理解你的错误,你想做String splitting:
var route = "From: Davao Del Sur (Phillipines) - To: Soccsksargen (Phillipines)";
var from = route.split("From: ")[1].split(" - ")[0];
console.log(from);
// How it works:
// Split String into array by using "From: " as seperator:
var array1 = route.split("From: ");
console.log(array1);
// take second element from array
console.log(array1[1]);
// split the element into another array using " - " as seperator:
var array2 = array1[1].split(" - ");
console.log(array2);
// take first element from array
console.log(array2[0]);
// done