[英]JQuery Async postback issue, how do I fix this?
我有以下JQuery代碼,它執行類似Stackoverflow的功能,用戶點擊評論鏈接並顯示評論或在這種情況下回復成員的狀態更新,通常它很有效,除非成員發布新狀態更新時在ASP.net MVC中使用ajax異步回發更新狀態更新列表。
如果你點擊列表中的新項目,它會將它們帶到一個新頁面而不是做JQuery想要做的事情。
<script type="text/javascript">
$(function() {
$("a[id ^='commentLink-']").click(function() {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
return false; //Prevent default action
});
});
</script>
注意:我認為導致它的原因是列表中的新項目實際上不在頁面上,因為列表是通過ajax更新的,因此在頁面刷新之前新的html不存在。
更新好的我如何使用Paolo Bergantino在觸發ASP.net MVC ActionResult的答案中所說的實時/事件功能?
查看jQuery 1.3中的新Events/live
功能
將處理程序綁定到所有當前和未來匹配元素的事件(如單擊)。
因此,當您添加新項目時,jQuery應該使用此方法向其添加click事件。
如果由於某些奇怪的原因你不想升級到jQuery 1.3,你可以查看livequery
插件。
編輯以響應更新 :
要使用.live
的實際代碼是這樣的:
$(function() {
$("a[id ^='commentLink-']").live('click', function(event) {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
event.preventDefault();
});
});
所做的更改主要在第二行,其中
$("a[id ^='commentLink-']").click(function() {
被...取代
$("a[id ^='commentLink-']").live('click', function(event) {
我現在也收到用於event.preventDefault();
的參數event
event.preventDefault();
這是建議您通過jQuery停止事件的方式。 如果return false;
但是,你能做到這一點。
我還沒有使用過.live
,但我認為應該這樣做。 但是,在嘗試此操作之前,請確保在服務器中獲得jQuery 1.3。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.