使用 jQuery 附加 HTML w/click 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/584605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:23:56  来源:igfitidea点击:

Appending HTML w/click event using jQuery

jqueryhtml

提问by mrblah

I want to append some HTML inside this div, and the HTML has to have a click event on it also.

我想在这个 div 中附加一些 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. There will be some dynamic text inside the new div so it has to by dynamically created.

我想在上面的 div 中插入一个新的 div,我想在我插入的新 HTML 上有一个点击事件。新 div 中会有一些动态文本,因此必须动态创建。

How can it be done?

怎么做到呢?

回答by fulmicoton

What about :

关于什么 :

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

回答by Andrew Ensley

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

回答by tomasofen

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. This is called deferred in the jquery documentation for "on" method. I hope this info saves time for someone reading this in the future :)

考虑到 on 方法的第二个参数,在本例中为“div”,是可选的,但如果您希望事件自动附加到动态创建的项目,则需要提供它。这在“on”方法的 jquery 文档中称为延迟。我希望这些信息可以为将来阅读此信息的人节省时间:)

回答by Rodolfo Jorge Nemer Nogueira

Andrew solve this problem to me! But .live is deprecated in the recent versions of jquery (as of 1.7). Use .on or .delegate on top.document to bind these events types. See:

安德鲁给我解决了这个问题!但是 .live 在 jquery 的最新版本中已被弃用(从 1.7 开始)。在 top.document 上使用 .on 或 .delegate 来绑定这些事件类型。看:

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

Congrats my friend!

恭喜我的朋友!