【问题标题】:jQuery CSS changes lost after ASP.NET AJAX asynchronous postbackASP.NET AJAX 异步回发后 jQuery CSS 更改丢失
【发布时间】:2012-04-02 19:06:51
【问题描述】:

我在 C# 中有以下内容:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <span id="header" class="hideMe">
            (other irrelevant tags and controls)
        </span>
        <div>
            (other irrelevant tags and controls)
        </div>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnSubmit" />
    </Triggers>
</asp:UpdatePanel>

还有下面的jQuery

if ($) {
  $(document).ready(function () {

    $('#header').click(function ($e) {
      if ($(this).hasClass('hideMe')) {
        $('#header').removeClass('hideMe');
        $('#header').addClass('showMe');
      }
      else {
        $('#header').removeClass('showMe');
        $('#header').addClass('hideMe');
      }
    }

  });
}

jQuery 工作得很好(即 ​​- 如果我单击标题跨度并且 hideMe 类是当前的,那么它将删除 hideMe 并添加 showMe,反之亦然)。

但是,当我单击 btnSubmit 时,会发生异步回发并导致标头跨度重置为其原始状态(这将应用 hideMe 类)。

如何让标题跨度保持在单击提交按钮时的状态,而不是恢复到页面加载时的状态?

【问题讨论】:

  • 这可以帮助你:*.com/questions/256195/…
  • @Gerson - 感谢您的链接!它给了我一个合理的解决方案。
  • Gerson - 如果您愿意将该链接作为答案,那么我会投票并检查它作为答案。
  • 现在作为答案。我很高兴它有帮助!

标签: jquery css ajax asp.net-ajax


【解决方案1】:

什么对我有用:

$(document).ready(function() { 
    // bind your jQuery events here initially 
}); 

var prm = Sys.WebForms.PageRequestManager.getInstance(); 

prm.add_endRequest(function() { 
    // re-bind your jQuery events here 
}); 

取自:jQuery $(document).ready and UpdatePanels?

【讨论】:

  • 这需要在脚本标签或脚本引用标签内还是没关系? IE。是否像
【解决方案2】:

尝试使用一些事件委托。

if ($) {
  $(document).ready(function () {

    $('body').delegate('#header','click',function ($e) {
      if ($(this).hasClass('hideMe')) {
        $(this).removeClass('hideMe');
        $(this).addClass('showMe');
      }
      else {
        $(this).removeClass('showMe');
        $(this).addClass('hideMe');
      }
    }

  });
}

编辑:如 cmets 中所述,这不会保持状态。为简单起见,我建议为此使用全局变量,但是您需要在异步调用上运行某种回调,以根据先前状态根据需要应用类。

【讨论】:

  • 只能半途而废。事件绑定将被保存(太好了!)但返回的#header 不一定有正确的类。可以存储在变量中,在 POST 之前获取状态并在成功回调中重新应用,POST 到服务器并让服务器发送回已经呈现的正确类等。