我正在使用Jquery Load()方法加载和插入html代码。 但是,当我试图找到一个我知道加载的html元素时,无法找到它。
//React to mouse clicks on table rows (that has company ID specified)
$("tr[id^=c_],tr[id^=e_]").live("click",function(event) {
//Fetch data from the server
var data = $('<td colspan="8" />').load('myUrRL?uid='+ID);
//Insert html-code into page
var tmp = $('<tr />').append(data).insertAfter($(this));
//Find one element we just inserted
var chartDiv = $("#chart_div_"+ID); // <-- FAILS !!!
});
//Now the element exists
var chartDiv = $("#chart_div_"+ID); // <-- SUCCESS
为什么我会遇到这个问题?我最简单的解决办法是什么?
答案 0 :(得分:2)
您必须等到内容加载完毕。
//React to mouse clicks on table rows (that has company ID specified)
$("tr[id^=c_],tr[id^=e_]").live("click",function(event) {
//Fetch data from the server
var data = $('<td colspan="8" />').load('myUrRL?uid='+ID,function(){
var chartDiv = $("#chart_div_"+ID); // <-- SUCCESS !!!
});
//Insert html-code into page
var tmp = $('<tr />').append(data).insertAfter($(this));
//Find one element we just inserted
var chartDiv = $("#chart_div_"+ID); // <-- FAILS !!!
});
//Now the element exists
var chartDiv = $("#chart_div_"+ID); // <-- SUCCESS
答案 1 :(得分:2)
jQuery.load
是jQuery AJAX函数的包装器,因此是一个异步操作。尝试使用回调:
var self = this;
var data = $('<td colspan="8" />').load('myUrRL?uid='+ID, function(){
//Insert html-code into page
var tmp = $('<tr />').append(data).insertAfter($(self));
//Find one element we just inserted
var chartDiv = $("#chart_div_"+ID); // <-- SUCCESS !!!
});