调用 JavaScript 方法的正确方法

发布于 2024-09-24 00:52:43 字数 176 浏览 1 评论 0原文

我应该按如下方式调用 JavaScript 方法吗?

onClick="Javascript:MyMethod();"

或者我可以这样称呼它:

onClick="MyMethod();"

有什么区别吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

泪是无色的血 2024-10-01 00:52:43

onclick 属性的值是代码,而不是 URI,因此这是正确的(尽管不是唯一的方法,请参阅下面的切线 #1):

onClick="MyMethod();"

这是不正确的 但基本上无害:

onClick="Javascript:MyMethod();"

有时人们认为后者使用 javascript 协议,例如链接,但事实并非如此。它完全在做别的事情。 onclick 属性中的代码语言是在页面级别定义的(默认为 JavaScript),因此您实际上要做的是在 JavaScript 中声明一个标签代码,然后调用 MyMethod。 JavaScript 有标签(参见下面的切线#2),尽管它们使用得不多。

onclick 属性与链接上的 href 属性完全不同:

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

由于我们将代码放在需要 URI 的位置,因此我们必须使用 < code>javascript 协议,因此浏览器知道我们在做什么。 javascript 是一种协议(如 httpmailto),Brendan Eich(JavaScript 的创建者)足够聪明地定义和注册(和实现)非常非常早,所以它得到了很好的支持。

最后:最好使 onclick 全部小写,而不是混合大小写,尽管只有在使用 XHTML 时才真正很重要。


切线 #1

也许有点偏离主题,但是:使用 HTML 属性来连接处理程序是完全有效的,并且跨浏览器运行良好,但它会将 JavaScript 事件连接与 HTML 混合在一起。有些人认为这是一件好事,而其他人则属于“不引人注目的 JavaScript”方面,并认为您应该稍后将所有内容连接起来。你做什么取决于你。当您的 HTML 设计人员和 JavaScript 编码人员不是同一个人时(大型团队中经常发生这种情况),这种不引人注目的方法特别有用。

不显眼的方法基本上是说:不要为此使用 HTML 属性,稍后从脚本中执行。因此,

<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>

您可能不会使用此 HTML:

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

与此 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
        }
    }
}

...其中 setTab 使用上下文来确定单击了哪个选项卡并采取相应的操作,并调用 hookUpTabs一旦 DOM 准备好。请注意,在设置点击处理程序时,我们将函数引用(而不是字符串)分配给选项卡 div 上的 onclick

我实际上不会在上面使用 onclick ,我会通过 addEventListener (标准)/ attachEvent (微软)函数使用 DOM2 处理程序。但我不想讨论标准与微软的问题。如果您开始使用不引人注目的 JavaScript,那么您也不需要使用库来为您处理这些内容(jQuery,< a href="http://prototypejs.org" rel="noreferrer">原型,闭包随便)。


切线 #2

另一个稍微偏离主题的切线:那么,这些 JavaScript 标签是什么?规范中的详细信息一如既往,但以下是在循环中使用带有定向 break 语句的标签的示例:

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);
    }
}

实例

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

北方。的韩爷 2024-10-01 00:52:43

这是一个不引人注目的替代方案。内联 JavaScript 代码使您的 HTML 难以理解。将 JavaScript(逻辑)与 HTML(表示)分开是正确的方法。在 jQuery 中,它会是这样的:

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

将其放入您的头部或外部脚本文件中。最好是定义 MyMethod 的位置。现在您的元素是干净的,并且所有方法调用都位于同一位置,而不是通过 HTML 分散。

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.

羁客 2024-10-01 00:52:43

不同的是,第一个是错误的。

第一个恰好可以工作,因为 someidentifier: 恰好是 JavaScript 中标签的语法,但由于那里不需要标签,所以没有必要添加它。

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.

遗忘曾经 2024-10-01 00:52:43

onclick 已经假定您正在执行 JavaScript 代码,因此不需要 javascript: 伪 URL。

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

一直在等你来 2024-10-01 00:52:43

AFAIK,您在这里定义了一个名为 Javascript 的跳转标签。你不应该这样做。这对通话没有影响。这是要走的路:

onClick="MyMethod();"

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();"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文