开发者

Can this be included in a .js file?

This code works when it is included in the HTML file, but I'd rather have it in a separate JS file.

Can that be done?

<script type="text/javascript">

window.onload = function() {
   var a = document.getElementById("mylink");

   a.onclick = function() {
      $('#c').empty();      
      return false;
   }
}
</script>

Update

I have tried this, but doesn't work...

$(document).ready(function(){

// other functions here

    window.onload = function() {
    var a = document.getElementById("mylink");
    a.onclick = function() {
        $('#c').empty();        
        return false;
    }
    }

    $('form').liv开发者_如何转开发e('submit', function(){

...


Sure thing - do this in the HTML file:

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

Then in /js/yourfile.js:

window.onload = function() {
   var a = document.getElementById("mylink");

   a.onclick = function() {
      $('#c').empty();      
      return false;
   }
}

This will work the same way as your code above.


Simply - Yes, it is possible.

Javascript files are treated the same way as in HTML Javascript.

Just make sure you have right order of including files.


If you were to put it in a separate JS file, and change your <script> tag to have a src, it would work exactly the same. You should be able to move the script tag around, but make sure it is in the proper order pending its dependencies like jQuery.


Yes, you can move this code into separate file.


As others have said your onload function will most likely be executed.

Be aware that it might turn out to be problem that if you set the onload directly, you can have only one function being executed on-load. If you include several scripts setting onload only the last one's function will run.

You might want to use addEventListener to be able to connect several functions or look into a js-library to help you with that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜