开发者

javascript linking onclick to a .js to a file

I开发者_Go百科 created a .js file, and then included it in the HTML pages by:

<script type="text/javascript" src="yourexternalfile.js"></script>

How do I call the function of the .js file using onclick = "...." ?

I know that it will be something like:

<input type="BUTTON" value="Exit" onclick="javascript: ???;" >

but I can't figure it out...


If you are using JQuery, you can do it like this,

       <input type="button" onclick="javascript: $.getScript('../scripts/yourfilepath' , function (){ youFunctionCall() ; } );" />

This will download the JS file when the button is cliked and shall execute the function called within.


Say your function was ...

function myFunction() {
    alert("hello!");
}

An example of the trigger would be ...

<input type="button" onclick="myFunction(); return false;" value="Click me!" />


To call a function inside an external file, make sure the file is loaded first and then call it as per normal (so long as it exposes itself to the scope you need it to).


include the external java script file in your page(preferably in the head tag) using

<script type="text/javascript" src="yourexternalfile.js"></script>

and then you can call any function defined in the js file


use <script type="text/javascript" src=""> to import the js file inside your page.


Knowing when a JS file is (a) loaded, and (b) done executing is tricky, as it isn't supported by all browsers.

I believe you're thinking something along the lines of:

var s = document.createElement("script"),
    f = document.getElementsByTagName('body')[0];
s.type = 'text/javascript';
s.src = "https://ajax.googleapis.com/ajax/libs/dojo/1.5.0/dojo/dojo.xd.js";

s.addEventListener("load", function() {
   console.log("script loaded");
});

f.appendChild(s);

Like I've mentioned above, it won't work for all browsers. And even if it does, it won't be very useful to you if you're actually trying to execute some code based on the JS that is pulled-in dynamically.

The only reliable way to execute something when a dependency is loaded is to wrap that dependency in a function. That way when the browser parses that JS it will execute that function, which will let you know that you can start using whatever it is that you wanted to bring in. This is exactly why JSONP works the way it works.

If this is what you want to do, take a look at RequireJS.


Have you tried actually putting in the name of the function? Like onclick='myFunction()'


I would suggest adding the on-click event in the JS file like so:

html:

<input type="button" id="myButton"/>

JS file:

var myButton = document.getElementById('myButton');
        myButton.onclick = function(){myFunction()};

This way you can program the element from the Javascript file. Just put it in a function that you call on-load.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜