JQuery toggle stops working after I make a server-side asp.net call?
I have a div called address which as a textarea. When I click a hyperlink, it toggles the div up and down. After clicking a an asp.net button the div collapses which is fine, but I noticed the url turns from www.abc.com/edit.aspx?Id=2 to www.abc.com/edit.aspx?Id2=2# and now the toggle does not work.
Here is the script:
$(document).ready(function () {
$('#myAddress').click(function () {
ShowHideAddressBox();
});
$('#arrowIndicator').click(function () {
ShowHideAddressBox();
});
});
function ShowHideAddressBox() {
var str = $("#myAddress").text();
if (str == "Hide") {
$("#myAddress").html("Click here");
$("#arrowIndicator").attr("src", "/Shared/Images/misc/arrow_state_grey_expanded.png");
}
else {
$("#myAddress").html("Hide");
$("#arrowIndicator").attr("src", "/Shared/Images/misc/arrow_state_grey_collapsed.png");
}
$('#checkAddress').t开发者_如何学编程oggle('normal');
}
The server-side button click just sets some values in a couple textboxes.
In my master page, I have the following line as well:
<asp:ScriptReference Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Name="MicrosoftAjax.js" Path="http://ajax.microsoft.com/ajax/3.5/MicrosoftAjax.js" />
What you're seeing is because the elements are being replaced, and they no longer have the handlers, you should replace this:
$(document).ready(function () {
$('#myAddress').click(function () {
ShowHideAddressBox();
});
$('#arrowIndicator').click(function () {
ShowHideAddressBox();
});
});
With a .live()
handler like this:
$(function () { //shortcut for $(document).ready(function () {
$('#myAddress, #arrowIndicator').live('click', ShowHideAddressBox);
});
You need to prevent the default action of the anchor (which is to follow the href). If you have got your anchor href set to '#' and do not use this it will append the # to the url in the address bar.
$('#arrowIndicator').click(function (ev) {
ev.preventDefault();
ShowHideAddressBox();
});
Actually you can use something like this:
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
//Code that runs after a post back with an update panel has occurred.
}
//Code on page load.
});
The code outside of the function EndRequestHandler would be the same as inside of it.
I used update panels when I was new to asp.net and programming in general. I quickly learned to use jQuery ajax, which is way a better solution than update panels. I suggest you check it out.
精彩评论