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

房东的猫 提交于 2019-12-02 13:44:10

You could just get the div element you want the code to be in, and then set the innerhtml to <script>your code here</script>

EDIT: Try assigning your function like so:

var myFunc = function() {
    //Code
}

Then you can call myFunc(parameters)

You can write your code like this :

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

Or you can write at this way :

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

i hope it will work.let me know.

i understand from you comment on my persevios answer you want to writer this code :

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

if it is true you can write like this :

    <!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>

i hope it will work.let me know

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!