JQuery的事件不与ASP.NET MVC管窥工作 [英] JQuery events don't work with ASP.NET MVC Partial Views

查看:106
本文介绍了JQuery的事件不与ASP.NET MVC管窥工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让JQuery的事件,在ASP.NET MVC局部视图工作。然而,在加载通过Ajax的局部视图,JQuery的似乎不能解雇任何在局部视图元素的事件。我怀疑,如果你正在使用其他的框架或JavaScript库加载部分HTML code使用Ajax这个问题也会出现。

I am trying to get JQuery events to work with partial views in ASP.NET MVC. However, after you load a partial view through Ajax, JQuery seems not able to fire events for any of the elements in the partial view. I suspect that this issue will also happen if you are using other frameworks or JavaScript libraries to load partial html code with Ajax.

例如,考虑下面的例子:

For instance, consider the following example:

控制器:

 public class TestController : Controller
    {

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult LoadPartialView()
    {
        return View("PartialView");
    }
}

Index.aspx的

Index.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"); %>

PartialView.ascx

PartialView.ascx

<div id="PartialView">
   Click <input type="button" id="button" value="here"></input> to display a javascript message.
</div>

在页面加载的第一次,你可以点击点击这里显示JavaScript消息,你会得到,说一个Javascript警告信息按钮,点击。但是,一旦你点击了点击这里载入局部视图,点击即能为我们带来了JavaScript警告消息没有任何效果的按钮。 看来,点击事件不被解雇了。

Once the page loads for the first time, you can click on the "Click here to display a Javascript message" and you will get a Javascript alert message that says "button clicked". However, once you click on the "Click here to load partial view", clicking on the button that is supposed to bring the Javascript alert message doesn't have any effect. It seems that the 'click' event is not being fired anymore.

有谁知道为什么这个问题与jQuery,以及如何解决出现?此问题也会发生与使用其他事件jQuery插件。

Does anyone know why this issue occurs with JQuery and how to fix? This issue also occurs with other JQuery plugins that use events.

推荐答案

我已经找到了解决办法:

I have found a solution :

中庸之道尽量做到:

$(document).on("click", "YOUR_SELECTOR", function(e){
  /// Do some stuff ...
});

相反的:

$("YOUR_SELECTOR").on("click", function(e){
  /// Do some stuff ...
});

这篇关于JQuery的事件不与ASP.NET MVC管窥工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆