jquery和append-on方法

jquery和append-on方法,jquery,html,Jquery,Html,我有这一页: <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/jav

我有这一页:

<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>
它正在做的是添加一个链接,我希望能够点击添加的链接并显示一条警报消息,但警报不起作用。我遗漏了什么?

将其更改为

$("#elem").on("click", "#test", function(){
        alert(12);
});
jQuery对此有很好的解释

$elements.on事件[,选择器][,数据],处理程序

当提供选择器时,.on类似于.delegate,因为它附加了一个>委托事件处理程序,由选择器过滤。当选择器被省略或null>时,调用类似于.bind。有一种不明确的情况:如果数据参数是字符串,>则必须提供选择器字符串或null,以便数据不会被误认为是>选择器。为数据传递一个对象,您将永远不必担心特殊情况

把它改成

$("#elem").on("click", "#test", function(){
        alert(12);
});
jQuery对此有很好的解释

$elements.on事件[,选择器][,数据],处理程序

当提供选择器时,.on类似于.delegate,因为它附加了一个>委托事件处理程序,由选择器过滤。当选择器被省略或null>时,调用类似于.bind。有一种不明确的情况:如果数据参数是字符串,>则必须提供选择器字符串或null,以便数据不会被误认为是>选择器。为数据传递一个对象,您将永远不必担心特殊情况


你没有活动的主播。由于没有其他包装,请将文档添加到该包装中:

$(document).on("click", "#test", function(){
    alert(12);
});
注意:这只在第一次单击时起作用,因为您将添加多个重复的ID

更好的方法:

$("#addElem").click(function () {
    $("#elem").append('<a class="test" href="#">this is a test</a><br />');
});
$(document).on("click", ".test", function(){
    alert(12);
});

你没有活动的主播。由于没有其他包装,请将文档添加到该包装中:

$(document).on("click", "#test", function(){
    alert(12);
});
注意:这只在第一次单击时起作用,因为您将添加多个重复的ID

更好的方法:

$("#addElem").click(function () {
    $("#elem").append('<a class="test" href="#">this is a test</a><br />');
});
$(document).on("click", ".test", function(){
    alert(12);
});

可以在创建函数时将其附加到已创建的元素:

$("#elem").append($('<a>', {
  id: "test.
  href: "#",
  text: "this is a test",
  click: function(e){
    e.preventDefault();
    alert(12);
  })
).append($("<br>"));

可以在创建函数时将其附加到已创建的元素:

$("#elem").append($('<a>', {
  id: "test.
  href: "#",
  text: "this is a test",
  click: function(e){
    e.preventDefault();
    alert(12);
  })
).append($("<br>"));

可能的重复项您没有为.on的委派事件使用正确的语法。您当前的用法与使用.clickfunction{…的用法相同。jquery在包含test的元素可用之前运行,这难道不是问题吗?您可能重复使用.on的委派事件没有使用正确的语法。您当前的用法与使用.clickfunction的用法相同{…jquery在包含test的元素可用之前运行不是问题吗?我认为这不是正确的js语法。另外,你能解释一下为什么它会修复它吗?@AlexanderKuzmin Exploration补充道,当你的评论出现时,他正在编辑。我认为这不是正确的js语法。另外,你能解释一下吗AlexanderKuzmin解释道,当你的评论进来时,他正在编辑。