【问题标题】:jquery script doesn't work after using .html()使用 .html() 后 jquery 脚本不起作用
【发布时间】:2013-04-23 14:48:05
【问题描述】:

当我使用 .html() 放置数据时,jQuery 脚本无法处理新数据。 代码是这样的:

<html>
<head>
<script>
$(document).ready(function(){
    $("#newhtml").on("click", function(){
        alert("I'm the NEW one!");
    });
    $("#put_new").on("click", function(){
        $("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
    });
});
</script>
</head>
<body>
<div id="newdiv"></div>
<input type="button" id="put_new" value="put new html" />
</body>
</html>

这是一个简单的示例,但我想要放置更多数据,并且我希望新元素以这种方式与脚本一起使用。 我试图在 stackoverflow.com 上搜索,但没有找到任何适用的。 非常感谢。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用这个:- http://jsfiddle.net/FQjUZ/

 $("#newdiv").on("click", "#newhtml", function(){
        alert("I'm the NEW one!");
    });
    $("#put_new").on("click", function(){
        $("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
    });

原因是,对于这种元素稍后添加到 DOM 的功能,您需要使用委托事件处理程序,而不仅仅是绑定。

事件处理程序仅绑定到当前选定的元素;在您的代码调用 .on() 时,它们必须存在于页面上。

委托事件的优点是它们可以处理来自以后添加到文档的后代元素的事件。通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要。例如,该元素可以是模型-视图-控制器设计中视图的容器元素,或者如果事件处理程序想要监视文档中的所有冒泡事件,则可以是文档。在加载任何其他 HTML 之前,文档元素在文档的头部是可用的,因此在此处附加事件是安全的,而无需等待文档准备好。

【讨论】:

  • 谢谢,这正是我想要的:)
【解决方案2】:

那是因为在执行您当前的.on() 语句时,元素#newhtml 不存在。

将您的事件绑定更改为:

$(document).on('click', '#newhtml', function(){
    alert("I'm the NEW one!");
});

您调用on() 的主要元素在调用时必须存在。在第二个参数中,您可以为绑定时可能不存在的元素指定选择器。

【讨论】:

    【解决方案3】:

    newHtml 上的事件将不起作用,因为您在将节点添加到 DOM 之前附加了事件,因此为了使其起作用,您需要在调用 html 方法后实现您的事件。

     $(document).ready(function(){
        $("#put_new").on("click", function(){
          $("#newdiv").html("<input type = 'button' id = 'newhtml' value = 'click on me'/>");
          $("#newhtml").on("click", function(){
               alert("I'm the NEW one!");
           });
       });
    });
    

    【讨论】:

      【解决方案4】:

      试试这样的。

      var f00 = "doStuff()";
      
      $("#newdiv").html('<input type="button" id="newhtml" value="click on me" onclick="' + f00 + '"/>');
      
      function doStuff() {
          //stuff
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多