简体   繁体   English

jQuery选择器在ASP.NET回发后不起作用(没有UpdatePanels,没有AJAX)

[英]jQuery selectors not working after ASP.NET postback (no UpdatePanels, not AJAX)

I need to make a change to an old page as quickly as possible, and the effort to AJAX-ify it in order to obviate postbacks would take too long (making a more correct version of it will have to come later, this new functionality needs to be in place ASAP). 我需要尽快对旧页面进行更改,而为了避免回发而对AJAX进行修改的工作将花费太长时间(制作更正确的版本将在稍后推出,这项新功能需要尽快就位)。 The javscript changes required are too complicated to attempt entirely in the plain JS the page currently uses for everything (it's enough of a mess as is), so I decided to implement the new functionality quickly using jQuery. 所需的javscript更改过于复杂,无法完全在该页面当前用于所有内容的纯JS中进行尝试(就算是一团糟),所以我决定使用jQuery快速实现新功能。

Everything works fine until there's a postback, after which the document ready function still runs, but the selectors no longer find anything. 一切正常,直到有回发,之后文档就绪功能仍然运行,但是选择器不再找到任何东西。 I'm not using ASP.NET AJAX, so there's no UpdatePanels or partial postbacks. 我没有使用ASP.NET AJAX,因此没有UpdatePanels或部分回发。

What's happening and how can I fix it in the simplest, fastest possible way? 发生了什么,如何以最简单,最快的方式修复它?

While $(document).ready() is ideal for one-time initialization routines, it leaves you hanging if you have code that needs to be re-run after every partial postback. 虽然$(document).ready()是一次性初始化例程的理想选择,但是如果您有需要在每次部分回发后重新运行的代码,它会使您陷入困境。 Of course there are ways to get around this. 当然,有一些方法可以解决此问题。 But can you try using .NET franeworks pageLoad() and bind your events there and see if selectors still work after postback. 但是您可以尝试使用.NET franeworks pageLoad()并将事件绑定到那里吗,看看回发后选择器是否仍然有效。

<script type="text/javascript">
  function pageLoad() {
    $("#Button1").on('click', function () {
       ...
    });
  }
</script>

If you have aa trigger attached to the DOM, and that element in the DOM gets replaced, the trigger will be lost. 如果您将触发器附加到DOM,而DOM中的该元素被替换,则触发器将丢失。 Such a trigger might look like $('#mydiv').on('click', function(){}); 这样的触发器可能看起来像$('#mydiv').on('click', function(){}); .

Instead, you have the attach the trigger to a DOM element that wont be replaced. 相反,您可以将触发器附加到将不会被替换的DOM元素上。 The easy way is to attach this to the document , but you'd be recommended to narrow the search. 最简单的方法是将其附加到document ,但是建议您缩小搜索范围。

Such a selector would look like 这样的选择器看起来像

$('document').on('click', '#mydiv', function() {});

This means that if the element #mydiv gets recreated, then the trigger is not lost. 这意味着,如果重新创建元素#mydiv,则触发器不会丢失。

You can read more about delegated events at http://api.jquery.com/on/ 您可以在http://api.jquery.com/on/上了解有关委托事件的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM