gpt4 book ai didi

javascript - 如果只将接收到的 HTML 的一部分插入到 DOM 中,为什么 jQuery 不执行 Javascript?

转载 作者:行者123 更新时间:2023-11-28 02:49:08 26 4
gpt4 key购买 nike

我有以下文件,将通过 AJAX 加载:

<div id="container">
<div>I need this in AJAX and the following scripts too</div>
<script type="text/javascript">
alert('I am executed');
</script>
<script type="text/javascript" src="some_included_script.js"></script>
</div>

<div>I do not need this in AJAX</div>

如果我按以下方式加载它:

  $.ajax({
url: url,
type: "GET",
cache: false,
dataType: "html",
success: function(data) {
$('#my_big_container').html(data);
}
});

然后所有脚本都被执行,并且 some_included_script.js 从服务器请求并执行。没问题。

但是如果我只需要“容器”内部的部分,请尝试以下代码:

  $.ajax({
url: url,
type: "GET",
cache: false,
dataType: "html",
success: function(data) {
$('#my_big_container').html(
$(data).filter('#container').html()
);
}
});

然后没有任何脚本被执行,也没有对 some_included_script.js 的请求(尽管“container”的纯 HTML 内容被正确插入到“my_big_container”中)。

为什么当我使用整个“数据”时脚本会被执行,而当我只过滤其中的一部分时脚本不会被执行?

如何加载接收到的数据的一部分并自动执行内部脚本?

最佳答案

我认为这有效:

而不是这个:

success: function(data) {
$('#my_big_container').html(
$(data).filter('#container').html()
);
}

试试这个:

success: function(data) {
$('#my_big_container').html(
$("<div>").html(data).find('#container')
);
}

关于javascript - 如果只将接收到的 HTML 的一部分插入到 DOM 中,为什么 jQuery 不执行 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4163597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com