2012-06-06 42 views
0

我有一個JSON對象JSON價值沒有得到追加到HTML中正確

var jsonString =[ 
    { 
     "key": "Monday, June 18, 2012", 
     "value": "10 00 AM|_mod,11 00 AM|_mod,12 00 PM|_mod,13 00 PM|_mod" 
    }, 
    { 
     "key": "Tuesday, June 19, 2012", 
     "value": "13 00 PM|_mod,13 30 PM|_mod,14 00 PM|_mod,14 30 PM|_mod,15 00 PM|_mod" 
    } 
]; 

我有兩個下拉式選單,我試圖以匹配與在關鍵的第一個下拉列表中選擇關鍵JSON並使用適當的值填充第二個下拉列表。 我想要的選項標籤看起來像這樣

<option value="10 00 AM|_mod">10 00 AM</option> 

但我看到這個

enter image description here

我認爲在10 6:00 AM空的空間| _mod是當DOM導致問題正在創建。

這是我的JS代碼。

$('#event_date').change(function() { 
    var event_date = $("#event_date").val(); // first drop-down val 
    var time_type = null; 
    var time = null; 
    for (var x = 0; x < jsonString.length; x++) { 
     if (event_date == jsonString[x].key) { 
      var value = jsonString[x].value; 
      console.log(value); // output: 10 00 AM|_mod,11 00 AM|_mod,12 00 PM|_mod,13 00 PM|_mod 
      var value_split = value.split(","); 
      for (var i = 0; i < value_split.length; i++) { 
       console.log(value_split[i]); // works fine at index 0 I get 10 00 AM|_mod 
       time_type = value_split[i].split("|"); 
       time = time_type[0]; 
       $('#timeslotIdentifier').append("<option value =" + value_split[i] + ">" + time + "</option>"); 
      }; 
     }; 
    }; 
}); 

是否存在編碼問題?我嘗試添加斷點,看起來很好,但是當我檢查元素時,我看到了這一點。

enter image description here

+0

這不是JSON,它是一個JavaScript數組。你的問題似乎與JSON沒有任何關係。 –

+0

不要魔法字符串像'「13 00 PM | _mod,13 30 PM | _mod,14 00 PM | _mod,14 30 PM | _mod,15 00 PM | _mod」'而不是擊敗json? – Eric

回答

4

你創建一個不帶引號的屬性值。

你應該使用jQuery來代替:

$('<option />').text(time).val(value_split[i]).appendTo('#timeslotIdentifier'); 
+0

忽略了那部分。非常感謝 !!欣賞它 –

1
$('#event_date').change(function() { 
    var event_date = $("#event_date").val(); // first drop-down val 
    var time_type = null; 
    var time = null; 
    for (var x = 0; x < jsonString.length; x++) { 
     if (event_date == jsonString[x].key) { 
      var value = jsonString[x].value; 
      console.log(value); // output: 10 00 AM|_mod,11 00 AM|_mod,12 00 PM|_mod,13 00 PM|_mod 
      var value_split = value.split(","); 
      for (var i = 0; i < value_split.length; i++) { 
       console.log(value_split[i]); // works fine at index 0 I get 10 00 AM|_mod 
       time_type = value_split[i].split("|"); 
       time = time_type[0]; 
       $('#timeslotIdentifier').append($("<option>").attr({value: value_split[i]}).text(time)); 
      }; 
     }; 
    }; 
}); 
1

jQuery的.val()在這種情況下肯定更好,但如果你不知道哪裏是錯誤,它是在這裏:

//Nope. (Missing quotes in HTML) 
$('#timeslotIdentifier') 
    .append("<option value =" + value_split[i] + ">" + time + "</option>"); 

//Yep. 
$('#timeslotIdentifier') 
    .append("<option value =\"" + value_split[i] + "\">" + time + "</option>");