设置 html <script> 的 src在 JavaScript 中 [英] setting src of html &lt;script&gt; in javascript

查看:41
本文介绍了设置 html <script> 的 src在 JavaScript 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法设置脚本标记的 src 属性:

I'm trying to set the src attribute of a script tag using:

document.getElementById("setScript").setAttribute("src","adventures/" + setting + ".js");

setScript"显然是脚本标签的id,设置变量是改变脚本的参数.我测试以确保 src 确实被设置,使用:

The "setScript" is obviously the id of the script tag, and the setting variable is a parameter to change the script. I tested to make sure the src was actually being set, using:

alert(document.getElementById("setScript").getAttribute("src"));

打印出 Adventures/[无论参数是什么].js.当我在 html 的 src 值中准确输入该值时,它将调用该函数.但是当它在 javascript 中更改时,它不会.有谁知道为什么会这样?

Which printed out adventures/[whatever the parameter was].js. When i type exactly that in the src value in the html, it will call the function. but when it is changed in the javascript, it dos not. does anyone know why this happens?

提前致谢

推荐答案

为了加载新的 javascript 文件,您必须使用 src 集创建一个新的脚本元素,然后将其添加到 html,例如将其附加到头部元素

in order to load a new javascript file you have to create a new script element with the src set and then add it to the html, eg append it to the head element

var script = document.createElement("script");
script.src = "/somescript.js";

var head = document.getElementsByName("head")[0];
head.appendChild(script);

这篇关于设置 html <script> 的 src在 JavaScript 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆