如何在 Javascript 中的脚本元素中添加局部变量和不同的函数

How to add local variables and a different function in script element in Javascript

我需要创建一个脚本元素,如下所示,

<div class="abcd">
    <script type="text/javascript">
  var a = "10";
  var b = "20";

        (function(d) {
            //lines of code of the function
        }(document));
    </script>
</div>

我试图通过首先通过 document.Createelement 选项创建脚本元素来完成这些。并将此脚本部分添加到 div。但无法在脚本部分添加代码部分。

需要同时添加 var 代码部分和函数。

请帮忙。

提前致谢


编辑----

我现在正在使用下面的代码,

    var headtg = document.getElementsByTagName('head')[0];
    var divElm = document.createElement('div');
    var scpt = document.createElement('script');
    scpt.type = 'text/javascript';
    var clName= "TEST";


    var myfunc = function innercode(i) {
        var a = i;
 var b = a;

        (function (d) {
  //codes
        }(document));
    }

    divElm.className = "ABC_" + clName;
    divElm.appendChild(scpt);
    headtg.appendChild(divElm);
    scpt.innerHTML = myfunc;

但输出结果为

<div class="abcd">
    <script type="text/javascript">
 function innercode(zID){var a = "10";var b = "20";;
    (function(d) {
            //lines of code of the function
        }(document));
    </script>
</div>

但我希望输出像,

<div class="abcd">
    <script type="text/javascript">
 var a = "10";
        var b = "20";;
        (function(d) {
            //lines of code of the function
        }(document));
    </script>
</div>

请指教

您可以只获取您希望代码所在的 div 元素,然后将 innerhtml 设置为 <script>your code here</script>

编辑: 尝试像这样分配您的功能:

var myFunc = function() {
    //Code
}

然后你可以调用 myFunc(parameters)

你可以这样写你的代码:

<html>
  <head>
      <script>
         var a = "10";
         var b = "20";

         function //here write you function name(d) {
        //lines of code of the function
          };
      </script>
  </head>
  <body>
  </body>
</html>

或者你可以这样写:

<html>
<body onload='write your javascript code here'>
</body>
</html>

我希望它会 work.let 我知道。

我从你对我的 persevios 回答的评论中了解到你想编写这段代码:

var headtg = document.getElementsByTagName('head')[0]; 
var divElm = document.createElement('div');
var scpt = document.createElement('script');
scpt.type = 'text/javascript';
var clName= "TEST";
divElm.className = "ABC_" + clName; divElm.appendChild(scpt);
headtg.appendChild(divElm);

function innercode(i) {
  var a = i; var b = a;
}
function (d) {
   //codes }(document));
 } 

如果是真的你可以这样写:

    <!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" charset="utf-8" >
        var headtg = document.getElementsByTagName('head')[0]; 
        var divElm = document.createElement('div');
        var scpt = document.createElement('script');
        scpt.type = 'text/javascript';
        var clName= "TEST";
        divElm.className = "ABC_" + clName; divElm.appendChild(scpt);
        headtg.appendChild(divElm);

        function innercode(i) {
         var a = i; var b = a;
        }
        function (d) {
         //codes }(document));
          } 
    </script>
</head>
<body>

</body>
</html>

我希望它会 work.let 我知道