21

後で DOM で作成される要素にイベント ハンドルを追加したいと考えています。

基本的に、私がやろうとしているのは、 をクリックするp#oneと新しい要素p#twoが作成され、次に をクリックp#twoして、「p#two」をクリックしたことを教えてくれることです。console.logをクリックした後、「p#two clicked」の結果が得られませんでしたp#two

on()にクリックイベントを追加するために使用しますp#two。私は何を間違っていますか?

ありがとう。

以下は私のコード例です:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>on() test</title>
  <link type="text/css" href="http://localhost/jquery-ui-1.8.20.custom/css/smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />
  <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-ui-1.8.20.custom.min.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {

        $('p#two').on('click', function() {
            console.log('p#two clicked');
        });


        $('p#one').click(function() {
            console.log('p#one clicked');
            $('<p id="two">two</p>').insertAfter('p#one');
        });

    }); // end doc ready
  </script>
</head>

<body>
    <p id="one">one</p>
</body>
</html>
4

3 に答える 3

29
$('body').on('click','p#two', function() {
    console.log('p#two clicked');
});

あなたも使うことができます

$(document).on('click', 'p#two', function() {

});

についてもっと読む.on()

あなたも使うことができます.delegate()

$('body').delegate('#two', 'click', function() {

});
于 2012-05-30T17:07:18.743 に答える
13

このように、常に dom に存在する親要素に $.on をバインドできます。

$(document).on('click','p#two', function() {
            console.log('p#two clicked');
        });

注意:document常に dom に存在する要素の任意の親に置き換えることができ、親が近いほど良いです。

$.onのドキュメントを確認

ライブは減価償却。代わりに $.on を使用してください。$.live および $.delegate の $.on と同等の構文

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

$.on他のすべてのメソッドは内部で $.on メソッドを経由するため、すべてのイベント処理の目的で使用することをお勧めします。

jQueryソースv.1.7.2からこれらの関数の定義を確認してください

bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
    return this.off( types, null, fn );
},

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},
die: function( types, fn ) {
    jQuery( this.context ).off( types, this.selector || "**", fn );
    return this;
},

delegate: function( selector, types, data, fn ) {
    return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
    // ( namespace ) or ( selector, types [, fn] )
    return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
} 

すべてのメソッドが使用$.onしていることと、$.offそれ自体を確認できます。したがって$.on、ほとんどの場合、それほど重要ではありませんが、少なくとも関数呼び出しを保存できます。

于 2012-05-30T17:07:22.463 に答える
-1

Jquery.onを使いたい

$('body').on('click','p#two', function() {
        console.log('p#two clicked');
    });
于 2012-05-30T17:06:23.160 に答える