简体   繁体   English

确保TextBox OnTextChanged(ASP.NET注入“setTimeout”)在OnClick之前触发

[英]Ensure TextBox OnTextChanged (ASP.NET injects a “setTimeout”) fires before OnClick

Consider the following scenario: 请考虑以下情形:

<asp:TextBox ID="txt" runat="server" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" CausesValidation="false" UseSubmitBehavior="false" />

when rendered, those two controls become: 渲染时,这两个控件变为:

<input name="txt" type="text" onchange="javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="txt">
<input type="button" name="btn" onclick="javascript:__doPostBack('btn','')" id="btn">

thanks to the setTimeout, the Click event is firing before the Change event. 感谢setTimeout,Click事件在Change事件之前触发。

After some research , I discovered that ASP.NET does this because of an old glitch in some older versions of IE. 经过一些研究 ,我发现ASP.NET之所以这样做,是因为在一些旧版本的IE中存在旧的故障。

However, this is causing problems because my button click hides the textbox, causing some "Invalid postback or callback" errors. 但是,这会导致问题,因为我的按钮单击会隐藏文本框,从而导致一些“无效的回发或回调”错误。

How can I fix the execution order, so the TextChanged always fires before Click? 如何修复执行顺序,因此TextChanged总是会在Click之前触发?

PS : I am willing to use Javascript/jQuery to change one of the events, but I'm in doubt about the performance of such solutions (since I would probably be forced to use eval for it) PS :我愿意使用Javascript / jQuery来改变其中一个事件,但我对这些解决方案的性能存在疑问(因为我可能会被迫使用eval)

I solved it using a bit of a hack, I'm still open for a better solution if anyone knows one. 我用一点点黑客解决了它,如果有人知道的话,我仍然愿意接受更好的解决方案。
For now, I'm calling this function on the page load: 现在,我在页面加载上调用此函数:

function removeSetTimeout() {
    var inputs = "select, input[type=text], input[type=number], input[type=date], input[type=time]";
    $(inputs).each(function (index, elem) {
        var change = $(elem).attr('onchange');
        if (change) {
            var patch = /setTimeout\('__doPostBack\(\\'.*?\\',\\'\\'\)', 0\)/.exec(change);
            if (patch) {
                change = change.replace(patch[0], patch[0].substring(12, patch[0].length - 5).replace(/\\/g, ''));
                $(elem).attr('onchange', change);
            }
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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