在您的代码中有两个问题:
$('#someTarget').append($(data).find('content').html());
$(data)
在将脚本插入 DOM 之前,会解析并执行脚本
假设你的意思$(data).find('.content').html()
是 html() 返回内容的 innerHTML,你只需要$(data)
.
试试这个:
<div class="content">
<style type="text/javascript">
function validate(){
alert('validate is working');
}
</style>
<div class="container">
<a href="#" onclick="javascript:validate();">my button</a>
</div>
</div>
现在有一个技巧:我<style>
用来包装脚本,应该在解释并插入 DOM 之后执行。
$.get('test.php', function(data) {
// parse HTML to DOM
var $data = $(data);
// take the scripts out
var $inlineScripts = $('style[type="text/javascript"]', $data).remove();
// Now append the DOM
$('#someTarget').append($data);
// And globalEval the scripts
$inlineScripts.each(function () {
$.globalEval(this.innerText);
});
});
Okay for your simple validate function that gets called by a click handler, you currently don't need my trick for inline scripts, however you will need it, when you have active scripts, that should be executed after the HTML is parsed and inserted.
Update: If you don't want the '.content' to be inserted, don't use html() - because it returns a string, so you do parse the html twice. Use instead .append( $(".container", $(data)) )
or .append( $(data).find(".container") )
.