2016-03-28 72 views
-3

我有這個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個變量。我在這裏錯過了什麼?

+0

你應該使用http://codereview.stackexchange.com/這個問題 –

回答

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時未定義。所以你的代碼彎曲工作。

得到它的工作,

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; 
    }); 
0

您需要這條線從改變:

origin = seg_city + seg_province + seg_country; 

origin += seg_city + seg_province + seg_country; 
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);