4

如何让 JQuery 以与处理 html 文件中的原始元素相同的方式处理新元素?例如,考虑以下示例:

<!DOCTYPE html>
<html>
    <head>
        <title>simple click to switch</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            $edit = "<div>edit</div>";
            $(document).ready(function () {
                $("div").click(function () {
                    $(this).after($edit);
                    $edit = $(this);
                    $(this).remove();
                });
            });
        </script>
    </head>
    <body>
        <div>switch me</div>
    </body>
</html>

我希望这个 JQuery 块允许我在单击时在 div“切换我”和“编辑”之间切换。但是,结果是,它可以识别原始 div,允许单个“切换”。但是 JQuery 无法识别新添加的 div。div 只能切换一次。我该如何解决这个问题?

4

1 回答 1

3

For dynamically added elements you need to use event delegation to register handlers

$(document).on('click', 'div', function () {
                $(this).after($edit);
                $edit = $(this);
                $(this).remove();
            });

Demo: Fiddle

Also read this

于 2013-08-13T00:42:06.957 回答