jQuery Mobile 只在頁面首次初始化時做一次整體渲染,之後用 ajax 動態產生的內容就必須靠局部渲染補上。
function queryPublishOrderList(trackOrDealOrInsp, userCode, type, pageNum){
var url = "https://xxx.xxx.xxx.xxx/Myapp/WorkOrderSelByTypeService.svc/"
+ "WorkOrderSimpSelByType/Json/"
+ trackOrDealOrInsp + "/" + userCode + "/" + type + "/" + pageNum;
$.ajax({
type: 'get',
dataType: "json",
url: url,
contentType: 'application/json',
data: [],
success: function(data) {
var sb = new StringBuffer();
$.each(data, function(i, item){
sb.append("<ul data-role='listview' data-inset='true' data-theme='c'>");
sb.append("<li>" + item.work_orders_id
+ "<span class='ui-li-count'>" + i + "</span></li>");
sb.append("<li><a href='inspectorder.html'>");
sb.append("<p><label>工單號:</label><span>"
+ item.work_orders_id + "</span></p>");
sb.append("<p><label>創建人:</label><span>"
+ item.founder_na + "</span></p>");
sb.append("</a></li></ul>");
});
$("#queryList").html(sb.toString());
},
error: function(){
alert("請求遠程服務錯誤!");
},
complete: function() {
$("p[data-role=content] ul").listview();
}
});
}重點在 complete 裡的 .listview(),它負責把新插入的 ul 初始化成 listview。
若要針對清單內部的 li 刷新,寫成:
$("p[data-role=content] ul li").listview("refresh");但如果容器尚未初始化就呼叫 refresh,會得到這則錯誤:
Cannot call methods on listview prior to initialization; attempted to call method 'refresh'
意思是:先 .listview() 初始化,才能 .listview('refresh')。
登入頁常有「記住帳號/記住密碼」兩個核選方塊。用 jQuery Mobile 寫時,勾選後讀到的值總是不對,原因是框架會把原生表單元素隱藏起來,另用 JS 產生美化的替身元素,兩者的狀態需要手動同步。
$('input[type="checkbox"]').bind('click', function() {
$(this).prop('checked').checkboxradio("refresh");
});
// 用 JS 改值時同樣要刷新
$('input[type="checkbox"]').attr('checked', false).checkboxradio("refresh");// 下拉選單
$("#selectbox").html(optionList).selectmenu('refresh', true);
// 核選方塊
$("input[type='checkbox']").attr("checked", true).checkboxradio("refresh");
// 單選按鈕組
$("input[type='radio']").attr("checked", true).checkboxradio("refresh");
// 清單選單
var myselect = $("select#foo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
// 滑桿
$("input[type=range]").val(60).slider("refresh");
// 開關(底層也是 slider)
var myswitch = $("select#bar");
myswitch[0].selectedIndex = 1;
myswitch.slider("refresh");select 的禁用寫法:
<select id="select-choice-1" disabled="disabled" aria-disabled="true"> <option value="standard">Standard: 7 day</option> <option value="rush">Rush: 3 days</option> </select>
button 的禁用寫法:
<input type="button" disabled="disabled" aria-disabled="true" value="不可用">
一句話總結:在 jQuery Mobile 裡,任何用程式改動過的表單元件都要記得呼叫對應的 refresh,畫面才會跟著更新。