简体   繁体   中英

Prevent postback in ie8 on dojo button click

I have the following code in my asp.net page:

<button dojotype="dijit.form.Button">
    <asp:Label ID="lblClear" runat="server" meta:resourcekey="lblClearResource1" />
        <script type="dojo/method" event="onClick" args="evt">
            return ClearCheckBoxes('<%=clientIds.ClientID%>');
        </script>
</button>

Where ClearCheckBoxes is the following:

function ClearCheckBoxes(obj1) {
    var chks = document.getElementsByTagName("input");
    for (i = 0; i < chks.length; i++) {
        if (chks[i].type == "checkbox") {
            if (chks[i].checked == true) chks[i].checked = false;
        }
    }
    document.getElementById(obj1).value = "";
    document.getElementById('<%=clientsIds.ClientID %>').value = "";

    return false;
}

This code works fine in all browsers, except in IE8, which causes a postback. Is there a way to disable a postback in IE8 in this scenario? Everything I've found online said return false; should work but that doesn't prevent the postback.

Typically, the default type for a button is submit , which will end up submitting a surrounding form if one exists. If this button is not intended to be submitting the form, adding type="button" to the <button> tag will stop it from behaving like a submit button.

Reduced example: (try removing type="button" to see the difference in IE8)

<form>
    <button type="button" data-dojo-type="dijit/form/Button">Button
        <script type="dojo/method" event="onClick" args="evt">
            this.set('label', 'Clicked');
        </script>
    </button>
</form>

Take a look at dojo/_base/event#stop ; here's the documentation , emphasis mine:

prevents propagation and clobbers the default action of the passed event

You can include that in your code.

require(['dojo/_base/event']);

<button dojotype="dijit.form.Button">
    <asp:Label ID="lblClear" runat="server" meta:resourcekey="lblClearResource1" />
        <script type="dojo/method" event="onClick" args="evt">
                dojo.stopEvent(evt); // dojo/_base/event extends dojo pre-2.0 
                return ClearCheckBoxes('<%=clientIds.ClientID%>');
        </script>
</button>

dojo/_base/event#stop works cross-browser, including (I believe) in IE8.

In case it's not feasible to require modules like that for your templates (I've never done anything like that myself), here's the code specific to preventing default behavior in IE:

evt = evt || window.event;
evt.cancelBubble = true;
on._preventDefault.call(evt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM