jQuery .load()/.ajax() 在附加后不在返回的 HTML 中执行 javascript

问题描述:

我尝试使用 .load()$.ajax 来获取一些需要附加到容器的 HTML,但返回的 HTML 中的 Javascript当我将它附加到元素时没有被执行.

I've tried using .load() and $.ajax to get some HTML that needs to be appended to a container, but the Javascript within the returned HTML is not being executed when I append it to an element.

使用.load():

$('#new_content').load(url+' #content > *',function() {
    alert('returned');
});

我也尝试切换到 $.ajax 调用.然后我从返回的 HTML 中提取脚本,然后将其附加到容器中,但同样的问题,在这种情况下,JS 没有被执行甚至没有被附加,据我所知,试图附加一个 <script> 像这样的 DOM 元素不受欢迎?

I've also tried switching to a $.ajax call. I then extracted the script from the returned HTML after which I appended it to the container, but same problem, the JS isn't being executed or even appended in this case, and as I understand it, trying to append a <script> to a DOM element like this is frowned upon?

使用$.ajax:

$.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,但变量被设置为从控制器返回的值.

Ideally I would run this javascript in a callback after I have appended the HTML, but variables are being set to values that are returned from a controller.

总而言之,我正在尝试获取一些包含在附加该 HTML 后需要运行的 JS 的 HTML,但是我没有使用 .load()>$.ajax() 因为返回的 HTML 中的脚本要么在附加时消失,要么根本不执行.

So in summary, I am trying to get some HTML which contains JS that needs to be run after that HTML has been appended, but I have had no luck using .load() or $.ajax() as the script in the returned HTML either disappears upon appending it, or it does not execute at all.

load() 与片段选择器一起使用时,脚本元素将在添加片段之前被剥离,因此 脚本不会被执行.

When load() is used with a fragment selector the script element will be stripped out before the fragment is added thus the script will not get executed.

使用不带后缀选择器的 URL 调用 .load() 时表达式,内容在脚本被传递之前传递给 .html()移除.这会在脚本块被丢弃之前执行它们.如果.load() 使用附加到 URL 的选择器表达式调用,然而,脚本在 DOM 更新之前被删除,因此不会被执行.下面是这两种情况的示例:

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:

试试吧

$.get('partial.html', function(result){
    $result = $(result);

    $result.find('#content').appendTo('#new_content');
    $result.find('script').appendTo('#new_content');
}, 'html');

演示:小提琴