ASP.NET C#中UpdatePanel异步回发时JavaScript函数失效问题求助
Fixing JavaScript Function Failure After UpdatePanel AsyncPostBack
Let's break down why your current setup isn't working and fix it step by step:
Key Issues in Your Original Code
- Function Scope Problem: You defined
direkyok()inside the$(document).ready()callback, which makes it a local function—meaning it's not accessible globally. That's why both your<a onclick="direkyok()">and theScriptManager.RegisterStartupScriptcall are failing (they can't find the function). - AsyncPostBack Doesn't Trigger
$(document).ready(): When an UpdatePanel refreshes asynchronously, the page's initialreadyevent won't fire again. Even if your function was accessible, any logic tied to the initial DOM load won't re-run for the updated content.
Updated Working Code
JavaScript
// Move the function to the global scope so it's accessible everywhere function direkyok() { $("body").toggleClass("mini-navbar mini-body"); } // Run on initial page load $(document).ready(function() { direkyok(); }); // Handle UpdatePanel AsyncPostBack completion var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(function() { // This runs every time an async postback finishes // If your UpdatePanel replaces elements that need the function, you don't need extra code here // because the global function is still available. If you need to re-apply state, call direkyok() here. });
HTML
<a onclick="direkyok()">Menü</a>
C# Code-Behind
ScriptManager.RegisterStartupScript(this, typeof(Page), "direkyok", "direkyok();", true);
Alternative: Event Delegation (More Robust for Dynamic Content)
If your <a> tag gets replaced by the UpdatePanel during async postbacks, using event delegation ensures the click handler still works without re-binding:
$(document).ready(function() { // Initial class toggle on page load $("body").toggleClass("mini-navbar mini-body"); // Use event delegation to bind the click event to a stable parent element $(document).on("click", "a[onclick='direkyok()']", function(e) { e.preventDefault(); // Optional, if you don't want default anchor behavior $("body").toggleClass("mini-navbar mini-body"); }); }); // Handle async postbacks if needed var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(function() { // Re-apply any necessary state or bindings here });
Why This Works
- Global Function: By defining
direkyok()outside thereadycallback, it's available to both the onclick attribute and the ScriptManager's startup script. - PageRequestManager: The
EndRequestevent listener ensures we can run logic after every async postback, which is crucial because UpdatePanel refreshes don't trigger$(document).ready(). - Event Delegation: This approach attaches the click handler to a stable parent element (like
document), so even if the<a>tag is re-rendered during an async postback, the click event still triggers the logic.
内容的提问来源于stack exchange,提问作者fabis
相关产品推荐
相关产品推荐

