所以我在jquery中包含了一個jquery ajax調用,一些css更改和重新定位div的這個長功能。這裏是我的代碼:腳本不等待Ajax返回?
$('.editable').click(function(e) {
//assign the attributes for the ajax call
$('#employeelist span').html("job: " + $(this).attr("editjob") + "<br />date: " + $(this).attr("editdate").substr(5));
$('#employeelist').attr("editjob", $(this).attr("editjob"));
$('#employeelist').attr("editdate", $(this).attr("editdate"));
//update the employee list with AJAX
$.get("getDaySchedule.php",
{'job': $('#employeelist').attr("editjob"), 'date': $('#employeelist').attr("editdate")},
function(responsetext){$('#employeelist ul').html(responsetext);},
"html"
);
//show the employee list
$('#employeelist').show()
.css('top',$(this).offset().top+25)
.css('left',($(this).offset().left+130))
.css('visibility', "visible")
.removeClass()
.addClass($(this).attr('class'));
//adjust the employee list if it goes outside the viewable area:
if ($('#employeelist').height() + $('#employeelist').offset().top > $(window).height()) {
newtop = ($('#employeelist').height() + $('#employeelist').offset().top) - $(window).height();
newtop = $('#employeelist').offset().top - newtop;
$('#employeelist').css('top',newtop);
};
if ($('#employeelist').width() + $('#employeelist').offset().left > $(window).width()) {
newleft = $('#employeelist').offset().left - 260;
$('#employeelist').css('left',newleft);
};
});
我遇到的問題是,它出現的代碼(它重新定位DIV如果是可視區域外),最後一節被運行之前Ajax調用完成。所以基本上div的高度很短,因爲它還沒有得到響應文本。這導致div太高並且越過可視區域,因爲它沒有被重新定位在正確的高度上。希望這是有道理的。有沒有我在代碼中丟失的東西?謝謝!
哦,謝謝你給我展示螢火蟲,這非常有用!不能相信我沒有使用過這個。是的,螢火蟲提醒我$(this).offset()爲空,我試圖根據哪個.editable項目被點擊重新定位#employeelist。我想現在這些函數在ajax回調函數中,它不再識別$(this)...有關如何更新它的任何想法? – Drew
啊我從來沒有想過,它只是一個範圍問題,因爲$(this)引用了ajax回調函數中的其他內容。我不得不將原來的$(this)存儲到它自己的變量中,然後我可以在回調函數中引用....感謝您的幫助! – Drew
您可能仍想查看我的答案和我提出的建議的結尾。 –