找不到原因,请大师帮帮忙。
双旋风
- 发布:2015-06-29 23:23
- 更新:2015-06-30 22:02
- 阅读:2181
原因在于mui.getJSON是异步执行的,但是createFragment方法同步执行返回的fragment,其实是没数据的;
var createFragment = function(ul, index, count, reverse) {
var length = ul.querySelectorAll('li').length;
var fragment = document.createDocumentFragment();
var li;
mui.getJSON('../js/test.js',function(data){
//异步执行,获得结果
for (var i = 0; i < count; i++) {
console.log(data[i].name);
li = document.createElement('li');
li.className = 'mui-table-view-cell';
li.innerHTML = '第' + (index + 1) + '个选项卡子项-' + (length + (reverse ? (count - i) : (i + 1))) + 'id:' + data[i].id + 'name:' + data[i].name;
fragment.appendChild(li);
}
});
//同步执行返回,此时ajax尚未响应
return fragment;
};
解决方案,简单修改代码如下:
$(pullRefreshEl).pullToRefresh({
down: {
callback: function () {
var self = this;
setTimeout(function() {
var ul = self.element.querySelector('.mui-table-view');
var length = ul.querySelectorAll('li').length;
var fragment = document.createDocumentFragment();
var li;
mui.getJSON('../js/test.js',function(data){
for (var i = 0; i < 2; i++) {
console.log(data[i].name);
li = document.createElement('li');
li.className = 'mui-table-view-cell';
li.innerHTML = '第' + (index + 1) + '个选项卡子项-' + 'id:' + data[i].id + 'name:' + data[i].name;
fragment.appendChild(li);
}
ul.insertBefore(fragment, ul.firstChild);
self.endPullDownToRefresh();
});
}, 1000);
}
}
});
进一步抽象的话,你可以慢慢优化。