gpt4 book ai didi

jquery - 使用jquery替换脚本src未执行

转载 作者:行者123 更新时间:2023-12-01 04:31:21 30 4
gpt4 key购买 nike

我想动态替换脚本的源 URL,只是为了加快开发阶段的速度,因此没有实际的生产使用。这种替换对于 CSS 或图像效果很好。但很难让它与 javascript src 一起工作。该脚本似乎没有执行,尽管是通过 src 加载的。

这是我所做的。

..................
return this.each(function() {
$(this).click(function() {
var t = $(this);
options.newVal = t.val();
var absUrl = '/root_path_still_within_the_same_domain/';
//options.oldVal is just to limit the replacement scope
var oldJsUrl = absUrl + options.oldVal + '.js';
var newJsUrl = absUrl + options.newVal + '.js';

var reJsUrl = $('script[type*=javascript][src*=' + options.oldVal + ']' || 'script[type*=javascript][src*=' + options.newVal + ']');

if (oldJsUrl.length && options.oldVal.length) {
reJsUrl.attr('src', newJsUrl);
}

options.oldVal = options.newVal;

});
});

......................

在 Firebug 中,目标旧 src url (/old_path_to_file.js) 被新的 (/new_path_to_file.js) 替换。所以替换有效。但它报告,(请参阅真正的绝对网址 http://,如果相关的话):

无法加载源:http://localhost/........js

因此脚本 src 被替换,但不被执行。如果这些东西被允许的话,我错过了什么吗?

我也尝试过使用$.getScript(absUrl + options.newVal + '.js');,但这并没有取代旧的src,只是向dom添加更多的js,这不是我想要的。这部分还有什么提示吗?

感谢您提供的所有可能的帮助。

最佳答案

如果您只想包含另一个脚本:

var script = document.createElement("script");
script.src = url; //Specify url here
script.type = "text/javascript";
$("body").append(script);

这将添加一个脚本并执行它...出于安全原因,您无法替换 src 并让它运行。您也不能只是“撤消”原始脚本所做的任何事情...根据您的问题,我认为这不是问题,但如果是,也许您不应该包含初始脚本标签,决定您需要什么,然后动态创建脚本元素,如上面所示。

关于jquery - 使用jquery替换脚本src未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226519/

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