按钮单击不会触发

button click won't fire

本文关键字:单击 按钮      更新时间:2023-09-26
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <div id="div1">Click here</div>
    </div>
    </form>
    <script type="text/javascript">
        var $ = function(e) { return document.getElementById(e); };
        var pageDefault = {
            btn1: $('Button1'),
            testfx: function() {
                alert('test');
            },
            init: function() {
                this.btn1.onclick = function() {
                    this.testfx();
                    return false;
                }
            }
        }
        pageDefault.init();
    </script>
</body>

为什么按钮 1 点击事件不会触发?

您可能需要

使用 $('<%= Button1.ClientID %>') 而不是 $('Button1') 。有关更多详细信息,请参阅此文章。

其他答案中提到的另一个问题是,事件处理程序指的是window this。要解决此问题,您可以通过以下方式重写处理程序:

this.btn1.onclick = function() {
    pageDefault.testfx();
    return false;
}
this

代码的那部分不在同一范围内。

试试这个

init: function() {
that = this // create's a that variable which refers to the current scope
this.btn1.onclick = function() {
    that.testfx(); // this now points to the scope of pageDefault
    // Same as doing pageDefault.testfx();
    return false;
}

演示

因为this.testfx();中的this不是pageDefault.testfx() Button1.testfx()

它应该是

this.btn1.onclick = function() {
    pageDefault.testfx();
    return false;
}
我认为

因为 BTN1 是一个 jQuery object.so 请使用这个 instade:

init: function() {
                this.btn1.click(function() {
                    this.testfx();
                    return false;
                });
            }