在jquery中load, getJSON,getScript, get 方法都是异步的,当我们在这些操作后面加上alert的时候,你会发现alert会在这些操作完成之前弹出
$(document).ready(function(){
$('#letter-d a').on('click', function(event){
event.preventDefault();
var html = '';
$.get('fragment/d.xml', function(data){//加载xml文档,生成xml DOM树(DOM对象)
$(data).find('entry').each(function(){//以每一个匹配的元素作为上下文来执行一个函数。
var $entry = $(this);
html += '<div class="entry">';
html += '<h3 class="term">'+$entry.attr('term')+'</h3>';
html += '<div class="part">'+$entry.attr('part')+'</div>';
html += '<div class="definition">'+$entry.children('definition').text();
//alert(typeof $entry.find('quote'));
//alert(typeof $entry.children('quote').attr('author'));
if($entry.children().is('quote')){//等价于$entry.find('quote').length
// alert($entry.children('quote').text());
html += '<div class="quote">';
$entry.children('quote').children('line').each(function(){//等价于$entry.find('line')
html += '<div class="quote-line">'+$(this).text()+'</div>';
});
if($entry.children('quote').attr('author')){//undefined为false ,string为true
html += '<div class="quote-author">'+$entry.children('quote').attr('author')+'</div>';
}
html += '</div>';
}
html += '</div>';
html += '</div>';
});
$('#dictionary').html(html);
});
alert(html);//当我点击按钮的时候,会先弹出框。然后才会显示内容,说明:异步
//$('#dictionary').html(html);不能写到这儿,因为get是异步的。
});
});
jQuery异步加载XML示例

被折叠的 条评论
为什么被折叠?



