简体   繁体   English

为什么 prop('outerHTML') 会剥离事件,我该如何阻止它?

[英]Why does prop('outerHTML') strip events, and how can I prevent it?

 const continueButton = $("<button>Doesn't work.</button>").click(() => {alert("hello")}); $(".content").append(continueButton.prop('outerHTML')); $(".content").append ($("<button>Works.</button>").click(() => {alert("hello")}))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> </div>

The reason I'm asking this question is because I need to pass the string version of some HTML to a function.我问这个问题的原因是因为我需要将一些 HTML 的字符串版本传递给 function。 For that reason, I can't use.append.因此,我不能使用.append。 but when i use the code above, it seems that the click event no longer works.但是当我使用上面的代码时,点击事件似乎不再起作用。

How can I get the HTML as a string, but have the click event still work?如何将 HTML 作为字符串获取,但点击事件仍然有效?


More context: I am using a library that expects me to add HTML to it as a string.更多上下文:我正在使用一个库,希望我将 HTML 作为字符串添加到它。 But I want to add HTML with a button on it that functions when it's clicked.但是我想添加 HTML 并在其上添加一个按钮,该按钮在单击时起作用。 I'm using jQuery to create the HTML, but when I try to pass the HTML string to the library, the buttons don't function.我正在使用 jQuery 创建 HTML,但是当我尝试将 HTML 字符串传递给库时,按钮不会 ZC1C4DF145268E17A477。

You can delegate the event to the content element and use button as target selector您可以将事件委托给内容元素并将button用作目标选择器

 // add delegated event listener before inserting buttons $('.content').on('click', 'button', (e) => console.log($(e.target).text())) const continueButton = $("<button>Doesn't work.</button>"); $(".content").append(continueButton.prop('outerHTML')).append ("<button>Works.</button>");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="content"> </div>

In line 1 the object has an event attached to it but this isn't reflected in HTML.在第 1 行中,object 附加了一个事件,但这并未反映在 HTML 中。 Therefore when you add the outerHTML to an element, the browser creates a new element but events are not defined in the HTML so they don't exist.因此,当您将outerHTML添加到元素时,浏览器会创建一个新元素,但事件未在 HTML 中定义,因此它们不存在。

If you embed the script inside the button HTML then it will work when you apply this HTML in different places: $('<button onclick="alert(\'hello\');">Test</button>') .如果您将脚本嵌入到按钮 HTML 中,那么当您在不同的位置应用此 HTML 时它将起作用: $('<button onclick="alert(\'hello\');">Test</button>')

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

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