简体   繁体   中英

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. For that reason, I can't use.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?


More context: I am using a library that expects me to add HTML to it as a string. But I want to add HTML with a button on it that functions when it's clicked. 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.

You can delegate the event to the content element and use button as target selector

 // 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. 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.

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>') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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