I have an AJAX response that contains some HTML, including <script>
elements.
This HTML should replace an existing element, but when I use:
$(element).replaceWith($(response))
I lose the script tags from it...
How can I insert the HTML exactly how it is sent?
This code is from facebook's sample app. Insert <div id="fb-root"></div>
in your document. The code requires jQuery to load up the script. In your case, replace //connect...../all.js
' with the <script>
elements.
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
It will return a string!!
$.get("ajax.php")
.success(function(returningHtmlString) {
$(element).replaceWith(returningHtmlString);
});
See jQuery.parseHTML( data [, context ] [, keepScripts ] )
The following should work
var content = jQuery.parseHTML(response, document, true)
$(element).replaceWith(content)
来源:https://stackoverflow.com/questions/8115179/jquery-replacewith-doesnt-take-script-tags