使用.load():@H_404_3@
$('#new_content').load(url+' #content > *',function() { alert('returned'); });
我也试过切换到$.ajax调用.然后我从返回的HTML中提取脚本,之后我将其附加到容器,但是同样的问题,JS在这种情况下没有被执行,甚至没有被附加,而且据了解,尝试附加< script>像这样的DOM元素被皱眉了?@H_404_3@
使用$.ajax:@H_404_3@
$.ajax({ url: url }).done(function(response) { var source = $("<div>").html(response).find('#overview_script').html(); var content = $("<div>").html(response).find('#content').html(); $('#new_content').html(content); $('<script>').appendTo('#new_content').text(source).html(); });
理想情况下,我会在附加HTML之后在回调中运行此JavaScript,但变量被设置为从控制器返回的值.@H_404_3@
所以总而言之,我试图获得一些包含JS的HTML,这些HTML需要在附加HTML之后运行,但是我没有运气使用.load()或$.ajax()作为返回的HTML中的脚本或者在附加它时消失,或者根本不执行.@H_404_3@
解决方法
When calling .load() using a URL without a suffixed selector
expression,the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however,the scripts are stripped out prior to the DOM being updated,
and thus are not executed. An example of both cases can be seen below:@H_404_3@
所以尝试@H_404_3@
$.get('partial.html',function(result){ $result = $(result); $result.find('#content').appendTo('#new_content'); $result.find('script').appendTo('#new_content'); },'html');