跨脚本标记的跨浏览器问题

时间:2013-07-28 17:06:02

标签: javascript html

我有以下代码将动态创建脚本标记。

<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);    

1 个答案:

答案 0 :(得分: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

更改doctype