追加内容后的jQuery click事件 [英] jQuery click event, after appending content

查看:84
本文介绍了追加内容后的jQuery click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道为什么下面的示例不起作用?

Wondering why the example below doesn't work?

<a id="load_list" href="#">Load the list</a>

<ul></ul>

<script type="text/javascript">
$(document).ready(function() {
    $('#load_list').click(function() {
        $('ul').append('<li><a href="#">Click here</a></li>');
        return false;
    });
    $('ul li a').click(function() {
        alert('Thank you for clicking');
        return false;
    });
});
</script>

推荐答案

由于定义click处理程序时要添加的元素不存在,因此它们是动态创建的.要解决此问题,您可以使用jQuery中的 delegate()方法.

Because the elements that you are appending do not exist when you define the the click handler, they are created dynamically. To fix this you can use the delegate() method from jQuery.

$('ul').delegate('a','click',function() {
    // your code here ...
});

在线示例: http://jsfiddle.net/J5QJ9/

这篇关于追加内容后的jQuery click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆