In jQuery, how to attach events to dynamic html el

2018-12-30 22:56发布

This question already has an answer here:

Suppose I have some jQuery code that attaches an event handler to all elements with class "myclass". For example:

$(function(){
    $(".myclass").click( function() {
        // do something
    });
});

And my html might be as follows:

<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>

That works with no problem. However, consider if the "myclass" elements were written to the page at some future time.

For example:

<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
    $("#anchor1").click( function() {
        $("#anchor1").append('<a class="myclass" href="#">test4</a>');
    });
});
</script>

In this case, the "test4" link is created when a user clicks on a#anchor1.

The "test4" link does not have the click() handler associated with it, even though it has class="myclass".

Any idea how I can fix this?

Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via Ajax/DHTML.

8条回答
爱死公子算了
2楼-- · 2018-12-30 23:33

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

查看更多
不流泪的眼
3楼-- · 2018-12-30 23:34

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

link text

$(function(){
    $(".myclass").live("click", function() {
        // do something
    });
});
查看更多
登录 后发表回答