javascript 异步回发后如何保持对同一控件的关注?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15895903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:30:05  来源:igfitidea点击:

How to maintain the focus on same control after asynchronous postback?

c#javascriptjqueryasp.netajax

提问by Lax_me

I have 3 textboxes , one is in updatepanel it will refresh for every 4 seconds. During refresh the controls which are not in update panel also loosing focus. I want to keep focus on those controls.

我有 3 个文本框,一个在 updatepanel 中,它将每 4 秒刷新一次。在刷新期间,不在更新面板中的控件也会失去焦点。我想继续关注这些控件。

Here is my code:

这是我的代码:

<asp:UpdatePanel ID="upnlChat" runat="server">
    <ContentTemplate >
        <asp:TextBox ID="txtChatBox" ReadOnly="true" TextMode="MultiLine" 
            CssClass="mymultitextboxclass" runat="server"></asp:TextBox>
     </ContentTemplate>
      <Triggers>
      <asp:AsyncPostBackTrigger ControlID="timerChat" />

      </Triggers>
    </asp:UpdatePanel>
    <asp:Timer ID="timerChat" Interval="4000" runat="server" ontick="timerChat_Tick" ></asp:Timer>
        <table>
        <tr><td>User: </td><td colspan="2"><asp:TextBox ID="txtUser" runat="server" ></asp:TextBox><br /></td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredUserName" runat="server" ErrorMessage="Username Required" ControlToValidate="txtUser" ></asp:RequiredFieldValidator> </td></tr>
        <tr><td>Message: </td><td><asp:TextBox ID="txtMsg" CssClass="mymsg" TextMode="MultiLine" onkeydown="if (event.keyCode == 13) { btnSend.focus(); this.form.submit();  }"  runat="server"></asp:TextBox></td>
        <td colspan="2"><asp:Button ID="btnSend" runat="server" onclick="btnSend_Click" 
                OnClientClick="scroll()" Text="send" />
        </td></tr>        
        </table>

Can anyone please help me?

谁能帮帮我吗?

回答by sparebytes

Here is a slightly modified version of @Darshan's script which uses jQuery. I like his solution because this 1 script will work with all UpdatePanels so you don't have to write code specifically for each and every UpdatePanel.

这是使用 jQuery 的 @Darshan 脚本的稍微修改版本。我喜欢他的解决方案,因为这 1 个脚本适用于所有 UpdatePanel,因此您不必专门为每个 UpdatePanel 编写代码。

My modifications are:

我的修改是:

  • Uses jQuery
  • Performs null checks
  • Doesn't pollute global namespace
  • Edit:Tabbing works as expected with TextBoxes with autopostback.
  • 使用 jQuery
  • 执行空检查
  • 不污染全局命名空间
  • 编辑:标签与自动回发的文本框按预期工作。


/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementId = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        if (fe != null) {
            focusedElementId = fe.id;
        } else {
            focusedElementId = "";
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementId != "") {
            $("#" + focusedElementId).focus();
        }
    });
});


Chosen.jQuery

选择.jQuery

This version will work with the Chosen jQuery plugin.

此版本将与 Chosen jQuery 插件一起使用。

/* Retain element focus after UpdatePanel postback
***************************************************/
jQuery(function ($) {
    var focusedElementSelector = "";
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(function (source, args) {
        var fe = document.activeElement;
        focusedElementSelector = "";

        if (fe != null) {
            if (fe.id) {
                focusedElementSelector = "#" + fe.id;
            } else {
                // Handle Chosen Js Plugin
                var $chzn = $(fe).closest('.chosen-container[id]');
                if ($chzn.size() > 0) {
                    focusedElementSelector = '#' + $chzn.attr('id') + ' input[type=text]';
                }
            }
        }
    });

    prm.add_endRequest(function (source, args) {
        if (focusedElementSelector) {
            $(focusedElementSelector).focus();
        }
    });
});

回答by Shahbaz Darkeaage Khan

回答by Darshan

Ohh Ok The problem is that the ASP.NET Javascript methode "WebForm_AutoFocus(...)" is not execute after a partial page update, so you can't use the built in function SetFocus(clientID) in the codebhind class. My solution register two eventhandlers one for beginRequest and one for endRequest. In the event method "beginRequest" i save the client control id. In the endRequest method i use this value to set the focus, e.g.: CODE:-

Ohh Ok 问题是 ASP.NET Javascript 方法“WebForm_AutoFocus(...)”在部分页面更新后不会执行,因此您不能在代码隐藏类中使用内置函数 SetFocus(clientID)。我的解决方案注册了两个事件处理程序,一个用于 beginRequest,一个用于 endRequest。在事件方法“beginRequest”中,我保存了客户端控件 ID。在 endRequest 方法中,我使用此值来设置焦点,例如:CODE:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shipper.aspx.cs" Inherits="shipper" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Restore Focus after background postback</title>
    <script language="javascript">
      var postbackElement = null;
      function RestoreFocus(source, args)
      {
        document.getElementById(postbackElement.id).focus();
      }
      function SavePostbackElement(source, args)
      {
        postbackElement = args.get_postBackElement();
      }
      function AddRequestHandler()
      {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(RestoreFocus);
        prm.add_beginRequest(SavePostbackElement);
      }
    </script>
</head>
<body onload="AddRequestHandler()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
        <asp:UpdatePanel runat="server" ID="updPanel1">
          <ContentTemplate>
            <asp:Panel ID="panel1" runat="server">
                <asp:RadioButtonList ID="rbList" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Rb 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Rb 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Rb 3" Value="3"></asp:ListItem>
                  <asp:ListItem Text="Rb 4" Value="4"></asp:ListItem>
                  <asp:ListItem Text="Rb 5" Value="5"></asp:ListItem>
                </asp:RadioButtonList><br />
                <asp:DropDownList ID="ddSample" runat="server" AutoPostBack="true">
                  <asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
                  <asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
                  <asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
                </asp:DropDownList>
            </asp:Panel>
          </ContentTemplate>
        </asp:UpdatePanel>
      </div>
    </form>
</body>
</html>

回答by Amit Singh

on timerChat_Tick event .do this....

在 timerChat_Tick 事件上。这样做....

txtChatBox.Focus();