简体   繁体   English

使用 jQuery 附加带有点击事件的 HTML

[英]Appending HTML w/click event using jQuery

I want to append some HTML inside this div, and the HTML has to have a click event on it also.我想在这个 div 中 append 一些 HTML ,并且 HTML 也必须有一个点击事件。

    <div id="myID">
        <p>hello, world!</p>
    </div>

I want to insert a new div inside of the above div, and I want a click event on the new HTML I insert there.我想在上面的 div 中插入一个新的 div,并且我想在我插入的新 HTML 上单击事件。 There will be some dynamic text inside the new div so it has to by dynamically created.新 div 内会有一些动态文本,因此必须动态创建。

How can it be done?怎么做到呢?

What about:关于什么:

$("#myID").click(
  function () {
     var someText = "my dynamic text";
     var newDiv = $("<div>").append(someText).click(function () { alert("click!"); });
     $(this).append(newDiv);
  }
)

As of jQuery 1.3, this will work:从 jQuery 1.3 开始,这将起作用:

<div class="myClass">
<p>hello, world!</p>
</div>


$(".myClass").live("click", function(){
    $(this).after("<div class='myClass'><p>Another paragraph!</p></div>");
});

See more about live events on this page:在此页面上查看有关现场活动的更多信息:

http://docs.jquery.com/Events http://docs.jquery.com/Events

IMPORTANT:重要的:

Take into account that the performance should be better if you use the most specific selector.考虑到如果您使用最具体的选择器,性能应该会更好。 For this case, if you want only affect the divs inside the "MyId" div, you should use:对于这种情况,如果您只想影响“MyId”div 中的 div,您应该使用:

$("#MyId").on("click", "div", function(e) {
    // Whatever you want to do when the divs inside #MyId div are clicked
});

VERY IMPORTANT:很重要:

Take into account that the second parameter for the on method, in this case "div", is optional, but you NEED to provide it if you want the event to be automatically attached to the dinamically created items.考虑到 on 方法的第二个参数,在本例中为“div”,是可选的,但如果您希望事件自动附加到动态创建的项目,则需要提供它。 This is called deferred in the jquery documentation for "on" method.这在 jquery 文档中称为“on”方法的延迟。 I hope this info saves time for someone reading this in the future:)我希望此信息可以为将来阅读此内容的人节省时间:)

Andrew solve this problem to me.安德鲁给我解决了这个问题。 But.live is deprecated in the recent versions of jquery (as of 1.7). But.live 在最新版本的 jquery(截至 1.7)中已弃用。 Use.on or.delegate on top.document to bind these events types: See:在 top.document 上使用 .on 或 .delegate 来绑定这些事件类型:参见:

$(document).on(".myClass", "click", function(){
    $(this).after("<div class='myClass'>Another paragraph!</div>");
});

Congrats my friend!恭喜我的朋友!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM