javascript - 如何获取控件的 id 会导致 javascript 中的回发

标签 javascript jquery asp.net

如何在 asp.net 中获取导致 PostBack 的控件的 ID。我用

document.getElementById("__EVENTTARGET")

但它只给出 objectHtmlInputElement 不是完整的 ID。我怎样才能只在 javascript 中而不是在代码中得到这个。我想要这个是为了在回发后专注于那个元素。请帮助..

最佳答案

您可以使用此 blog 中提到的功能要获取回发控件 id,将此 id 存储在 hiddenfield 中并使用 JS 从 hiddenfield 获取该 id

 protected void Page_Load(object sender, EventArgs e)
    {    
        if (Page.IsPostBack)
           HiddenField1.Value = getPostBackControlName();
    } 

private string getPostBackControlName()
{
    Control control = null;
    //first we will check the "__EVENTTARGET" because if post back made by       the controls
    //which used "_doPostBack" function also available in Request.Form collection.
    string ctrlname = Page.Request.Params["__EVENTTARGET"];
    if (ctrlname != null && ctrlname != String.Empty)
    {
        control = Page.FindControl(ctrlname);
    }

    // if __EVENTTARGET is null, the control is a button type and we need to
    // iterate over the form collection to find it
    else
    {
        string ctrlStr = String.Empty;
        Control c = null;
        foreach (string ctl in Page.Request.Form)
        {
            //handle ImageButton they having an additional "quasi-property" in their Id which identifies
            //mouse x and y coordinates
            if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
            {
                ctrlStr = ctl.Substring(0, ctl.Length - 2);
                c = Page.FindControl(ctrlStr);
            }
            else
            {
                c = Page.FindControl(ctl);
            }
            if (c is System.Web.UI.WebControls.Button ||
                     c is System.Web.UI.WebControls.ImageButton)
            {
                control = c;
                break;

            }
        }
    }
    return control.ID;
}

关于javascript - 如何获取控件的 id 会导致 javascript 中的回发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14054783/

相关文章:

javascript - 使用 iframe 识别窗口焦点/模糊事件

jquery - 选择具有没有特定类的子元素的元素列表

c# - 如何从静态 WebMethod 绑定(bind) gridview

无需在 IIS 上发布即可调试 ASP.NET Core 应用程序

javascript - react 函数说 "is not a function"

javascript - 滚动文本的水平视差效果

javascript - 仅在选择 1/3 + 1/3 单选选项时使按钮可单击

javascript - ASP.NET 上的 Jquery 掩码不起作用

javascript - 使用 Chrome 打开正文中包含 HTML 的 Outlook

JavaScript:在不使用 `eval` 的情况下将平面数组转换为树状结构