在Jquery中连接变量

时间:2016-03-28 10:03:22

标签: jquery

我有这个jQuery代码,它的工作原理。但丑陋:

var origin = "";
$.each(json, function(i,o){
    origin += "<option value="+o.city_id+">"+o.city_name+"</option><option value="+o.province_id+">"+o.province+"</option><option value="Indonesia">"Indonesia"</option>";
});

$("#product_seg_area").append(origin);

然后我决定清理代码,使它看起来更干净:

var origin = "";
$.each(json, function(i,o){
    var seg_city += "<option value="+o.city_id+">"+o.city_name+"</option>";
    var seg_province += "<option value="+o.province_id+">"+o.province+"</option>";
    var seg_country += "<option value="Indonesia">"Indonesia"</option>";
    origin = seg_city + seg_province + seg_country;
});

$("#product_seg_area").append(origin);

但似乎将3个变量连接到一个变量使我的代码停止工作。我错过了什么?

3 个答案:

答案 0 :(得分:1)

$.each(json, function(i,o){
    var seg_city += "<option value="+o.city_id+">"+o.city_name+"</option>";
    var seg_province += "<option value="+o.province_id+">"+o.province+"</option>";
    var seg_country += "<option value="Indonesia">"Indonesia"</option>";
    origin = seg_city + seg_province + seg_country;
});

问题是seg_city未定义。在第一轮中,您尝试将html连接到undefined。所以你的代码很有用。

为了让它发挥作用,

var seg_city, seg_country, seg_province;
$.each(json, function(i,o){
        seg_city = "<option value="+o.city_id+">"+o.city_name+"</option>";
        seg_province = "<option value="+o.province_id+">"+o.province+"</option>";
        seg_country = "<option value="Indonesia">"Indonesia"</option>";
        origin = seg_city + seg_province + seg_country;
    });

答案 1 :(得分:1)

试试这个......

var origin = "";
$.each(json, function(i,o){
    var seg_city = "<option value='"+o.city_id+"'>"+o.city_name+"</option>";
    var seg_province = "<option value='"+o.province_id+"'>"+o.province+"</option>";
    var seg_country = "<option value='Indonesia'>"Indonesia"</option>";
    origin += seg_city + seg_province + seg_country;
});

$("#product_seg_area").append(origin);

答案 2 :(得分:0)

您需要更改此行:

origin = seg_city + seg_province + seg_country;

origin += seg_city + seg_province + seg_country;