开发者

Proper way of calling a JavaScript method [duplicate]

This question already has answers here: When do I need to specify the JavaScript protocol? (5 answers) 开发者_JAVA技巧 Closed 3 years ago.

Is there a reason why I should call a JavaScript method as follows?

onClick="Javascript:MyMethod();"

Or can I just call it like this:

onClick="MyMethod();"

Is there any difference?


The value of an onclick attribute is code, not a URI, so this is correct (though not the only way you might do it, see tangent #1 below):

onClick="MyMethod();"

This is incorrect but largely harmless:

onClick="Javascript:MyMethod();"

Sometimes people think the latter is using the javascript protocol, like on links, but it isn't. It's doing something else entirely. The language of the code in the onclick attribute is defined at page level (and defaults to JavaScript), and so what you're actually doing is declaring a label in your JavaScript code, and then calling MyMethod. JavaScript has labels (see tangent #2 below), though they're not used much.

The onclick attribute is totally different from the href attribute on links:

<a href="javascript:MyMethod();">

There, since we're putting code where a URI is expected, we have to specify a URI using the javascript protocol, so the browser knows what we're doing. javascript is a protocol (like http or mailto) that Brendan Eich (creator of JavaScript) was clever enough to define and register (and implement) very, very early on so it's well-supported.

Finally: Best to make onclick all lower case, not mixed case, although it only really matters if you use XHTML.


Tangent #1

Perhaps a bit off-topic, but: Using the HTML attributes for hooking up handlers is perfectly valid and works well cross-browser, but it intermixes your JavaScript event hookup with your HTML. Some people see that as a good thing, others belong to the "unobtrusive JavaScript" side and think you should hook everything up later. What you do is up to you. The unobtrusive approach is particularly useful when your HTML designers and your JavaScript coders are not the same people (as happens frequently on large teams).

The unobtrusive approach basically says: Don't use the HTML attributes for this, do it later from script. So instead of

<ul id='tabset'>
    <li onclick="setTab(1);">Tab 1</li>
    <li onclick="setTab(2);">Tab 2</li>
    <li onclick="setTab(3);">Tab 3</li>
</ul>

you might have this HTML:

<ul id='tabset'>
    <li>Tab 1</li>
    <li>Tab 2</li>
    <li>Tab 3</li>
</ul>

combined with this JavaScript:

function hookUpTabs() {
    var tabset, tab;
    tabset = document.getElementById('tabset');
    for (tab = tabset.firstChild; tab; tab = tab.nextSibling) {
        if (tab.tagName == "LI") {
            tab.onclick = setTab; // Hooks up handler, but there are better ways
        }
    }
}

...where setTab uses context to figure out which tab was clicked and act accordingly, and hookUpTabs is called as soon as the DOM is ready. Note that where we're setting up the click handler, we're assigning a function reference, not a string, to the onclick on the tab div.

I wouldn't actually use onclick in the above, I'd use DOM2 handlers via the addEventListener (standard) / attachEvent (Microsoft) functions. But I didn't want to get into standard vs. Microsoft stuff. And you don't either, if you start doing unobtrusive JavaScript, use a library to handle that stuff for you (jQuery, Prototype, Closure, whatever).


Tangent #2

Another mildly off-topic tangent: So, what are these JavaScript labels then? Details in the spec as always, but here's an example of using labels with a directed break statement in a loop:

var innerIndex, outerIndex;

// Label the beginning of the outer loop with the (creative) label "outerloop"
outerloop: for (outerIndex = 0; outerIndex < 10; ++outerIndex) {

    for (innerIndex = 0; innerIndex < 50; ++innerIndex) {

        if (innerIndex > 3) {
            break; // Non-directed break, breaks inner loop
        }

        if (innerIndex > 2 && outerIndex > 1) {
            // Directed break, telling the code that we want to break
            // out of the inner loop *and* the outer loop both.
            break outerloop;
        }

        display(outerIndex + ":" + innerIndex);
    }
}

Live Example


Here is an unobtrusive alternative. Inline JavaScript code makes your HTML difficult to follow. Separating your JavaScript (logic) from your HTML (presentation) is the way to go. In jQuery it would be something like this:

$(function() {
    $('#the-element').click(function() {
        MyMethod();
    });
});

Put that in your head or an external script file. Preferably where your MyMethod is defined. Now your element is clean, and all of your method calls are located in the same place, rather than spread out through the HTML.


The difference is that the first one is wrong.

The first one just happens to work because someidentifier: happens to be the syntax for a label in JavaScript, but since there is no need for a label there, there is no point of adding it.


onclick already presumes you're executing JavaScript code, so there's no need for a javascript: pseudo-url.


AFAIK, you are defining a jump label with the name Javascript here. You shouldn't do that. This makes no difference to the call. This is the way to go:

onClick="MyMethod();"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜