Stop executing JavaScript
I have:
$('body').data('data开发者_如何转开发1', '<script type="text/javascript">console.debug('execute');</script><div>example</div>');
and:
<div id="content"></div>
when I do:
$(document).ready(function () {
$('#content').html($('body').data('data1'));
});
then JavaScript is executed. How to prevent executing? Is it possible?
You have to strip the script
tags from your HTML string.
var p = new DOMParser(),
doc = p.parseFromString("<html><body>...</body></html>", "text/xml");
$('script', doc).remove();
This works with Firefox/Chrome, although I don't know about other browsers. Note this will only work with well-formed (x)html.
EDIT: If you also want the JS, you can amend the previous code thus:
var scripts = [];
$('script', doc).remove().each(function() {
scripts.push($(this).html());
});
Mind you, you don't even have to remove the script
tags. Now that the response is in its separate DOM document, it will not mess up your own scripts, and you can access whatever content you need from it using easy $('selector', doc)
jQuery.
The only way you are going to stop the script from executing is to remove it from your data. The prototype framework does this using a regular expression like below:
<script[^>]*>([\\S\\s]*?)<\/script>
精彩评论