質問

Well I have the following inline JavaScript events in my .HTML file and I want to put their JavaScript alternatives in a .JS file. Then I'll link the .JS file to the .HTML file. Here are the events:

oncontextmenu
onmousedown
onload
onclick
onerror
onmouseover
onmouseout
役に立ちましたか?

解決

<div id = "yourElement"></div>
<script>
    var yourElement = document.getElementById("yourElement"); //get the element
    yourElement.oncontextmenu = function () {
        //oncontextmenu triggered!
    }
    yourElement.onmousedown = function () {
        //onmousedown triggered!
    }
    yourElement.onload = function () {
        //onload triggered!
    }
    //ecc..
</script>


EDIT:

here's my fiddle: http://jsfiddle.net/durZL/

Note: if you put the script in the header you should tell to the javascript to run the code when the page is fully loaded, or else you are not able to get the element,
jQuery already does this for you, but if don't want to use it this is the right way to do it:

window.onload = function () {
   //here is the code that will run after the page is fully loaded
   //DOM elements can be safely manipulated here
}

他のヒント

You're going to have to attach event handlers from your external JS file.

If your using jQuery (would recommend for this kind of selector heavy stuff):

$('some selector').on('some event', function( evt ) { /* Do some stuff here */ });

Or if you don't want to use jQuery:

document.querySelector('some selector').addEventListener('some event', function( evt ) { /* Do some stuff here */ });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top