When defining a JavaScript call, like so:
<input type="button" onclick="someJavaScriptFunction" />
What is the best way to write the actual call? I've seen numerous method:
javascript:someJavascriptFunction();
or
justSomeJa开发者_运维问答vaScriptFunction();
or
withoutTheSemicolon()
Are there any benefits or caveats to any of the methods? I realize that using addEventListener
is more flexible in certain cases.
The best practice itself is to use JavaScript itself to attach the events:
Firefox, Chrome, Safari, Opera...
document.getElementById('someID').addEventListener('click', function() {
function1();
function2();
function3();
});
IE:
document.getElementByID('someID').attachEvent('onclick', function() {
function1();
function2();
function3();
});
Combine the two to get it to work.
Also, use premade frameworks like MooTools or JQuery to make this even easier.
If you want best practice, separate markup from script content. Assign your event handlers in script
elements. As you say, using addEventListener
is one way of doing this, although you have to use attachEvent
as well if you want to support versions of Internet Explorer before version 9.
It's perfectly valid, however, to assign onevent
properties. For instance:
<script>
window.onload = function() {
document.getElementById('yourID').onclick = function() {
alert('element clicked');
};
};
</script>
This may well suit your purpose adequately, if you only have a few items.
javascript:someJavascriptFunction();
We use javascript:
as URL in href
attribute or in bookmark address filed (bookmarklets).
For example:
<a href="javascript:myFunction()">click me</a>
We use semicolon to attach more than one JavaScript instruction:
<span onclick="alert('first');alert('second')">click me</span>
addEventListener
allows to attach many functions to same event:
element.addEventListener ('click', firstFunction);
element.addEventListener ('click', secondFunction);
With or without the semicolon makes no difference, however the event is actually a line of javascript not just a function name so you could use the semicolon to add multiple functions like so:
<input type="button" onclick="function1();function2();function3();" />
I'm not sure javascript: will work at all, that is just if you attach a function as an href on a link, not as an event handler like below:
<a href="javascript:function1();function2();function3();" >A link</a>
javascript:someJavascriptFunction();
Explicitly state to use javascript, in the case that you may have multiple/different scripts types such as ECMA Script.
someJavascriptFunction()
is fine if you only have Javascript(s) on your page (rather than having multiple script types.
someJavascriptFunction();doSomethingElse();return false;
Semi-colon used to chain/have multiple statements.
So there is no 'best' way, just what makes most sense, and is your preferred convention (in most cases).
addEventListener is the best way
精彩评论