简体   繁体   中英

Activate script on click event

If I want to activate a piece of code on click I would put the code in the head like this:

   <script type="text/javascript">
        function myFeed() {

...code... 

}
    </script>

And then call it like this:

<button onclick="myFeed();"> click </button>

But now Im facing a problem using FeedBurner. All I have is this:

<script src="http://feeds.feedburner.com/nu/gbKB?format=sigpro" type="text/javascript" ></script>

How can I assign a function to it like I did in the first example and call it in the body??

On click just add the javascript to the DOM,

Heres how to do it

I would also add an ID to the script you add it to make it easier if you have to remove it.

This method i've provided adds it to the head of the DOM.

function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
  • Line 1 Opens the function with parameters of script location and where to add it eg myscript.js , head
  • Line 2 Cets the element you told it in the pos varible
  • Line 3 Creates script tags
  • Line 4 Adds script type
  • Line 5 Adds source
  • Line 6 Adds the script,tag,type to the DOM

Link to resource (JS Dom Manipulation)

Starting from Liam's answer, just some details:

function myFeed()
{
  document.write('<script src="http://feeds.feedburner.com/nu/gbKB?format=sigpro" type="text/javascript" ></script>');
}

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM