Button's .click() command not working in Chrom

2019-06-14 10:09发布

问题:

I have a button

<asp:Button ID="submitRegionsButton" runat="server" Text="OK" OnClick="OnSubmitRegion" />

and when I click it, everything works as expected, however when I have a javascript function call it using btn.click(), the click command is not executed. The button is found properly but just doesn't then work or run the OnClick function in my code behind

Any ideas? It works in IE, haven't tested firefox though

Okay, tested in firefox, doesn't work there. Everything works right up until the actual call to .click(), no idea why :/

Code that calls the click:

    function dropDownProductBlur() {
        if (isItemClicked) {
            var combo = $find("<%= productDropDown.ClientID %>");
            var btnSubmitProd = $get(combo.get_id() + "_Footer" + "_submitProductsButton");
            if (btnSubmitProd)
                btnSubmitProd.click();
        }
    }

Just for understanding, the button is contained within a dropdown, and when the dropdown closes, it "clicks" the button (or, well, is supposed to..) clicking the button manually works, and the find works and finds the button properly.

回答1:

I recently ran into this problem myself. I believe the issue is that in javascript, this .click() is either treated as the component's onClientClick event, or something else entirely. Not sure on this.

In any case, my solution: Instead of calling btnSubmitProd.click(), do __doPostBack('Foo', 'Bar'); where Foo is an arbitrary name (typically the component, so "submitRegionButton") and Bar is an arbitrary value for that name, typically the event (so "click") (also, there are TWO underscores there, not one). Then, in your codebehind:

try {
  if (Request["__EVENTTARGET".ToString() == "Foo" && Request["__EVENTARGUMENT"].ToString() == "Bar" {
    //call the codebehind directly here
    OnSubmitRegion(null null);
  }
}

I assume your codebehind function is of the form protected void OnSubmitRegion(object sender, EventArgs e). If you need the values for any of those variables, things get a little more complicated. If not, give the above a try.