1

私はこのページを持っています:

<html>
<head></head>
<body>

<div id="elem"></div>
<button id="addElem">Add Element</button>

<script src="jquery-1.9.1.js" type="text/javascript"></script>

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

        //add element to elem div
        $("#addElem").click(function () {
            $("#elem").append('<a id="test" href="#">this is a test</a><br />');
        });

        //remove added elements on click event
        $("#test").on("click", function(){
            alert(12);
        });

    });
</script>

</body>
</html>

何をしているのか、リンクを追加しています。追加したリンクをクリックして警告メッセージを表示できるようにしたいのですが、警告が機能していません。私は何が欠けていますか?

4

3 に答える 3

1

You do not have an anchor for the event. Since you have no other wrapper, add the document to that:

$(document).on("click", "#test", function(){
    alert(12);
});

NOTE: This will ONLY work on the first click as you would be adding multiple ID's that would be duplicates.

Better way:

$("#addElem").click(function () {
    $("#elem").append('<a class="test" href="#">this is a test</a><br />');
});
$(document).on("click", ".test", function(){
    alert(12);
});
于 2013-05-01T20:59:32.913 に答える