1
<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>

button1 クリック イベントが発生しないのはなぜですか?

4

4 に答える 4

4

$('<%= Button1.ClientID %>')の代わりに使用する必要がある場合があります$('Button1')。詳細については、この記事を参照してください。

他の回答で言及されている別の問題は、イベントハンドラーがthiswhich isを参照することですwindow。これを修正するには、次の方法でハンドラーを書き直すことができます。

this.btn1.onclick = function() {
    pageDefault.testfx();
    return false;
}
于 2012-06-14T18:23:54.183 に答える
1

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;
}

デモ

于 2012-06-14T18:23:57.630 に答える
0

は ないのでthis_ this.testfx();pageDefault.testfx()Button1.testfx()

そのはず

this.btn1.onclick = function() {
    pageDefault.testfx();
    return false;
}
于 2012-06-14T18:26:13.823 に答える
0

btn1はjqueryオブジェクトであるため、次のように使用します。

init: function() {
                this.btn1.click(function() {
                    this.testfx();
                    return false;
                });
            }
于 2012-06-14T18:29:35.570 に答える