【问题标题】:Cross browser issue with script tag脚本标签的跨浏览器问题
【发布时间】:2013-07-28 17:06:02
【问题描述】:

我有下面的代码可以动态创建脚本标签。

<html>
<head>
    <title>Applying</title>
</head>
<body>

<script>
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
        function(m,key,value) {
            vars[key] = value;
        });
    return vars;
}
var variable1 = getUrlVars()["parameter1"];    

var myScript = document.createElement('script');

myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin@domain.net');

document.body.appendChild(myScript);                              
</script>

<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='https://www.google.com?'">

</body>
</html>

但不知何故,上面的代码在 IE 中不起作用,但在 Chrome 中却可以正常工作。我不确定是什么原因?有人可以帮我吗?

这整件事在 IE 中不起作用。

var myScript = document.createElement('script');

myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin@domain.net');

document.body.appendChild(myScript);    

【问题讨论】:

  • 我没有看到您向该脚本元素添加任何实际的 JS 代码 - 那么当它“工作”时您究竟希望它做什么......?
  • 您生成的&lt;script&gt; 似乎没有src 或任何内容。
  • 另外,它怎么不工作?你有错误吗?
  • 它在 Chrome 中的作用是什么?
  • @mplungjan 为什么会这样?他们将其附加到正文中

标签: javascript html


【解决方案1】:

您可以使用以下函数动态添加脚本元素。

   var create_script = function(data) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.text = data;

        //if you have to debug dynamically loaded script in chrome use the following - sourceURL has changed in the recent versions of chrome devetools.
        //script.text = data + "\n\n //@ sourceURL=" + ns + ".js\n";

        //append the script element to body or head or where it seems fit.
        document.body.appendChild(script);
    }

“data”参数是构成脚本标记部分的实际 javascript 代码/URL。您的代码中缺少此内容。

编辑: 对于非标准属性,您可能希望根据http://www.w3schools.com/DTD/dtd_attributes.asp 更改文档类型

【讨论】:

  • 但是我还有其他属性可以添加。并且 document.body.appendChild 也可以在 IE 中使用?我相信这是一个已知问题?
  • 这可能取决于浏览器 - 但脚本标签应该支持这里提到的属性 - w3schools.com/tags/tag_script.asp 以及这里提到的全局属性 - w3schools.com/tags/ref_standardattributes.asp
  • 是的,它不能在 IE 中运行,我需要确保它也应该在 IE 中运行。
  • 您是否尝试过将文档类型修改为以下 ttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="nofollow" target="_blank">w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [ ]>
  • @TechGeeky IE 没有这样的已知问题,但是 IE 很慢,它对元素的行为以及它的所有被解析的父浏览器与其他浏览器略有不同。您可以尝试在 onload 事件上运行脚本吗?我非常希望它可能会起作用。
猜你喜欢
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 2021-10-02
  • 2011-03-25
相关资源
最近更新 更多