javascript linking onclick to a .js to a file

半腔热情 提交于 2019-12-05 09:36:34

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.

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