【发布时间】:2010-02-03 20:27:08
【问题描述】:
我正在尝试让 JQuery 事件与 ASP.NET MVC 中的部分视图一起使用。但是,在通过 Ajax 加载局部视图后,JQuery 似乎无法为局部视图中的任何元素触发事件。我怀疑如果您使用其他框架或 JavaScript 库通过 Ajax 加载部分 html 代码,也会发生此问题。
例如,考虑以下示例:
控制器:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LoadPartialView()
{
return View("PartialView");
}
}
索引.aspx
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
alert('button clicked');
});
});
</script>
<div>
<%using(Ajax.BeginForm("LoadPartialView", new AjaxOptions { UpdateTargetId="PartialView"})){ %>
Click <input type="submit" value="here" /> to load partial view.
<% } %>
</div>
<br /><br />
<% Html.RenderPartial("PartialView"); %>
部分视图.ascx
<div id="PartialView">
Click <input type="button" id="button" value="here"></input> to display a javascript message.
</div>
页面首次加载后,您可以单击“单击此处以显示 Javascript 消息”,您将收到一条 Javascript 警报消息,显示“按钮已单击”。但是,一旦您单击“单击此处加载部分视图”,单击应该带来 Javascript 警报消息的按钮就没有任何效果。 似乎不再触发“点击”事件。
有谁知道为什么 JQuery 会出现这个问题以及如何解决?使用事件的其他 JQuery 插件也会出现此问题。
【问题讨论】:
标签: jquery asp.net-mvc ajax events