Javascript: 2 ways to insert new function dynamically

来源:互联网 发布:剑灵人女身材数据 编辑:程序博客网 时间:2024/05/22 07:53

I personally recommend the first way:


function addFunc() {
  
var sFunc = ""

    
+"function myOnUnLoad()"
    
+"{"
      
+"alert('unload...');"
    
+"};"
    
+"window.document.body.onunload = myOnUnLoad;";

  window.eval(sFunc);
}


Second way, by this way you have to write down all your code in a external js file, in this case, let us say myjs.js file:

function addFunc()
{
  var o 
= window.document.createElement("script"
);
  o.type
="text/javascript"
;
  o.src
="myjs.js"
;

  
//
if you use o.innerHTML="..." or o.innerText="..." here, you will get a runtime error.
  
//that is why you have to use a external js file, and use o.scr="myjs.js" to insert function code


  window.document.getElementsByTagName(
"head")[0].appendChild(o);
}


//-- code in myjs.js file
window.document.body.onunload = function ()
{
  alert(
"unload..."
);
}
原创粉丝点击