在 JavaScript 中添加事件的最佳方式是什么?

发布于 2024-07-04 17:05:42 字数 689 浏览 5 评论 0原文

我看到在 JavaScript 中设置事件的两种主要方法:

  1. 直接在标签内添加事件,如下所示:

    do foo

  2. 通过 JavaScript 设置它们,如下所示:

    do bar

并在 部分内的

Event.observe(window, 'load', function() {
    $('bar').observe('click', doBar);
}

我认为第一种方法更容易阅读和维护(因为 JavaScript 操作直接绑定到链接),但事实并非如此干净(因为即使页面未完全加载,用户也可以单击链接,这在某些情况下可能会导致 JavaScript 错误)。

第二种方法更干净(当页面完全加载时添加操作),但更难知道操作是否链接到标签。

哪种方法最好?

一个杀手级的答案将不胜感激!

I see 2 main ways to set events in JavaScript:

  1. Add an event directly inside the tag like this:

    <a href="" onclick="doFoo()">do foo</a>

  2. Set them by JavaScript like this:

    <a id="bar" href="">do bar</a>

and add an event in a <script> section inside the <head> section or in an external JavaScript file, like that if you're using prototypeJS:

Event.observe(window, 'load', function() {
    $('bar').observe('click', doBar);
}

I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).

The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.

Which method is the best?

A killer answer will be fully appreciated!

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

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

发布评论

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

评论(6

无戏配角 2024-07-11 17:05:43

YUI 和 jQuery 等库提供了仅在 DOM 准备好后添加事件的方法,可以在 window.onload 之前。 它们还确保您可以添加多个事件处理程序,以便您可以使用来自不同源的脚本,而不同的事件处理程序不会相互覆盖。

所以你的实际选择是;

一。 如果您的脚本很简单并且是唯一会在页面上运行的脚本,请创建一个 init 函数,如下所示:

window.onload = function () {
    init();
}
function init() {
    // actual function calls go here
    doFoo();
}

二。 如果您有许多脚本或计划混搭来自不同来源的脚本,请使用库及其 onDOMReady 方法来安全地添加事件处理程序

Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. They also ensure that you can add multiple event handlers so that you can use scripts from different sources without the different event handlers overwriting each other.

So your practical choices are;

One. If your script is simple and the only one that will ever run on the page, create an init function like so:

window.onload = function () {
    init();
}
function init() {
    // actual function calls go here
    doFoo();
}

Two. If you have many scripts or plan to mashup scripts from different sources, use a library and its onDOMReady method to safely add your event handlers

浮生面具三千个 2024-07-11 17:05:42

我认为第一种方法更容易阅读和维护

我发现事实恰恰相反。 请记住,有时多个事件处理程序将绑定到给定的控件。

在一个中心位置声明所有事件有助于组织站点上发生的操作。 如果您需要更改某些内容,则不必搜索调用函数的所有位置,只需在一处进行更改即可。 当添加更多应该具有相同功能的元素时,您不必记住向它们添加处理程序; 相反,通常让它们声明一个类就足够了,甚至根本不更改它们,因为它们在逻辑上属于一个容器元素,该元素的所有子元素都连接到一个操作。 从实际代码来看:

$('#itemlist table th > a').invoke('observe', 'click', performSort);

这将事件处理程序连接到表中的所有列标题以使表可排序。 想象一下使所有列标题可单独排序所需的努力。

I think the first method is easier to read and maintain

I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.

Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:

$('#itemlist table th > a').invoke('observe', 'click', performSort);

This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.

夜无邪 2024-07-11 17:05:42

我个人的偏好是在外部 js 文件中使用 jQuery,这样 js 就与 html 完全分离。 Javascript 应该是不引人注目的,因此内联(即第一个示例)在我看来并不是真正的最佳选择。 当查看 html 时,您使用 js 的唯一标志应该是脚本包含在 head 中。

附加(和处理)事件的一个示例可能是这样的,

var myObject = {

    allLinkElements: null,  

    init: function()
    {
        // Set all the elements we need
        myObject.setElements();

        // Set event handlers for elements
        myObject.setEventHandlers();
    },

    clickedLink: function()
    {
        // Handle the click event
        alert('you clicked a link');
    },

    setElements: function()
    {
        // Find all <a> tags on the page
        myObject.allLinkElements = $('a');

        // Find other elements...
    },

    setEventHandlers: function()
    {
        // Loop through each link
        myObject.allLinkElements.each(function(id)
        {   
            // Assign the handler for the click event
            $(this).click(myObject.clickedLink);
        });

        // Assign handlers for other elements...
    }
}

// Wait for the DOM to be ready before initialising
$(document).ready(myObject.init);

我认为如果您想组织所有 js,这种方法很有用,因为您可以使用特定对象来执行任务,并且所有内容都很好地包含在内。

当然,让 jQuery(或另一个众所周知的库)完成艰苦工作的巨大好处是(很大程度上)解决了跨浏览器支持,这使生活变得更加轻松

My personal preference is to use jQuery in external js files so the js is completely separate from the html. Javascript should be unobtrusive so inline (ie, the first example) is not really the best choice in my opinion. When looking at the html, the only sign that you are using js should be the script includes in the head.

An example of attaching (and handling) events might be something like this

var myObject = {

    allLinkElements: null,  

    init: function()
    {
        // Set all the elements we need
        myObject.setElements();

        // Set event handlers for elements
        myObject.setEventHandlers();
    },

    clickedLink: function()
    {
        // Handle the click event
        alert('you clicked a link');
    },

    setElements: function()
    {
        // Find all <a> tags on the page
        myObject.allLinkElements = $('a');

        // Find other elements...
    },

    setEventHandlers: function()
    {
        // Loop through each link
        myObject.allLinkElements.each(function(id)
        {   
            // Assign the handler for the click event
            $(this).click(myObject.clickedLink);
        });

        // Assign handlers for other elements...
    }
}

// Wait for the DOM to be ready before initialising
$(document).ready(myObject.init);

I think this approach is useful if you want to keep all of your js organised, as you can use specific objects for tasks and everything is nicely contained.

Of course, the huge benefit of letting jQuery (or another well known library) do the hard work is that cross-browser support is (largely) taken care of which makes life much easier

枯寂 2024-07-11 17:05:42

我相信第二种方法通常是首选,因为它将有关操作的信息(即 JavaScript)与标记分开,就像 CSS 将表示与标记分开一样。

我同意这会使查看页面中发生的情况变得更加困难,但是像 firebug 这样的好工具将在这方面为您提供很大帮助。 如果您将 HTML 和 Javascript 的混合保持在最低限度,您还会发现可以获得更好的 IDE 支持。

随着项目的发展,这种方法确实会发挥作用,并且您会发现想要将相同的 javascript 事件附加到许多不同页面上的一堆不同元素类型。 在这种情况下,使用附加事件的单一步骤变得更加容易,而不必搜索许多不同的 HTML 文件来查找调用特定函数的位置。

I believe the second method is generally preferred because it keeps information about action (i.e. the JavaScript) separate from the markup in the same way CSS separates presentation from markup.

I agree that this makes it a little more difficult to see what's happening in your page, but good tools like firebug will help you with this a lot. You'll also find much better IDE support available if you keep the mixing of HTML and Javascript to a minimum.

This approach really comes into its own as your project grows, and you find you want to attach the same javascript event to a bunch of different element types on many different pages. In that case, it becomes much easier to have a single pace which attaches events, rather than having to search many different HTML files to find where a particular function is called.

初心未许 2024-07-11 17:05:42

根据我的经验,这有两个要点:

1)最重要的是保持一致。 我认为这两种方法不一定更容易阅读,只要你坚持下去。 只有当这两种方法都在项目中使用时(或者在同一页面上使用更糟糕)时,我才会感到困惑,因为那时我必须开始搜索调用,并且不立即知道在哪里查找。

2) 第二种,即Event.observe(),当对多个事件采取相同或非常相似的操作时具有优势,因为当所有这些调用都在同一位置时,这一点变得显而易见。 此外,正如康拉德指出的那样,在某些情况下,这可以通过一次调用来处理。

In my experience, there are two major points to this:

1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.

2) The second kind, i.e. Event.observe() has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.

只有影子陪我不离不弃 2024-07-11 17:05:42

您还可以使用addEventListener(不在IE 中)/attachEvent(在IE 中)。

查看:http://www.quirksmode.org/js/events_advanced.html

这些允许您将一个函数(或多个函数)附加到现有 DOM 对象上的事件。 它们还具有允许稍后解除连接的优点。

一般来说,如果您使用大量的 javascript,那么使 javascript 可读(而不是 html)会很有用。 因此,您可以说 html 中的 onclick=X 非常清楚,但这既是代码缺乏分离(各部分之间的另一种语法依赖关系)的情况,也是您必须阅读 html 和 javascript 以了解页面的动态行为。

You can also use addEventListener (not in IE) / attachEvent (in IE).

Check out: http://www.quirksmode.org/js/events_advanced.html

These allow you to attach a function (or multiple functions) to an event on an existing DOM object. They also have the advantage of allowing un-attachment later.

In general, if you're using a serious amount of javascript, it can be useful to make your javascript readable, as opposed to your html. So you could say that onclick=X in the html is very clear, but this is both a lack of separation of the code -- another syntactic dependency between pieces -- and a case in which you have to read both the html and the javascript to understand the dynamic behavior of the page.

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