我有以下 JQuery 代码,它具有类似 Stackoverflow 的类似功能,其中用户单击评论链接并显示评论或在这种情况下回复成员(member)的状态更新,通常它工作得很好,除非成员(member)发布新的状态更新,它使用 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?
最佳答案
查看新的 Events/live
jQuery 1.3 中的功能
Binds a handler to an event (like click) for all current - and future - matched element.
因此,当您添加新项目时,jQuery 应该使用它向它们添加点击事件。
如果出于某种奇怪的原因您不想升级到 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
以用于 event.preventDefault();
这是建议您通过 jQuery 停止事件的方式。不过,如果 return false;
可以解决问题,您可以保留它。
我还没有使用过 .live
,但我认为这应该可以解决问题。不过,请确保在尝试之前在服务器中安装了 jQuery 1.3。 :)
关于javascript - JQuery 异步回发问题,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466637/