使用 jQuery 的 document.Ready 函数将事件附加到元素

发布于 2024-09-07 15:43:50 字数 608 浏览 8 评论 0原文

普通风格

<a href="#" id="myLink" onclick="myFunc();">click me</a>

function myFunc() {
    alert('hello!');
}

jQuery 风格

<a href="#" id="myLink">click me</a>

$(document).ready(function() {
    $("#myLink").click(function() {
        alert('hello!');
    });
});

我刚刚开始使用 jQuery,但我想知道这两者之间有什么区别。我应该更喜欢 jQuery 方法吗?这样做有什么好处吗?

恕我直言,我不喜欢用 jQuery 方法阅读 html 时,不知道链接的作用。我发现 jQuery Attach 方法在附加到多个元素时非常有用(例如 $("#myTable tr").click(function(e) {...});),但是当处理单个元素我不知道应该使用哪个。

Normal style

<a href="#" id="myLink" onclick="myFunc();">click me</a>

function myFunc() {
    alert('hello!');
}

jQuery style

<a href="#" id="myLink">click me</a>

$(document).ready(function() {
    $("#myLink").click(function() {
        alert('hello!');
    });
});

I've just started using jQuery, but I'm wondering what the difference between these two is. Should I prefer the jQuery method? Are there any advantages when doing it this way?

Imho I don't like that when reading the html with the jQuery method, there's no clue as to what the link does. I've found the jQuery attach method really useful when attaching to multiple elements (e.g. $("#myTable tr").click(function(e) {...});), but when dealing with a singular element I don't know which I should be using.

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

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

发布评论

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

评论(4

樱花细雨 2024-09-14 15:43:50

我喜欢第二种方法,有几个原因。

  1. 它将所有 javascript 内容保存在一个地方;你是对的,当你阅读 HTML 时,你不知道点击链接会做什么,但另一方面,如果你内联定义事件处理程序,那么当你阅读 javascript 时,你不知道什么时候函数将被调用。我喜欢尽可能地将我的“层”分开。

  2. 它提倡有时所谓的“不引人注目的 javascript”,以及优雅的降级您的申请。优雅降级(或“渐进增强”)的想法是,您将链接设置为真正的链接,该链接将转到单独的页面,但随后您使用 javascript 劫持点击事件,并在不离开页面的情况下提供相同的功能。这样,如果用户没有 javascript(假设他们是使用屏幕阅读器的残疾用户),应用程序仍然可以工作。

  3. 它使 javascript 更加可重用;假设我根据 CSS 类等通用内容定义了将事件处理程序绑定到的元素。然后我可以将该 JavaScript 放到各种页面上并让它“正常工作”。例如,对于自动保存之类的事情,我一直这样做。

I like the second approach, for a few reasons.

  1. It keeps all of the javascript stuff in one place; you're right that when you read the HTML you don't know what clicking the link will do, but the flip side is that if you define the event handler inline, then when you read the javascript, you don't know when the function will be called. I like to keep my "layers" separate as much as possible.

  2. It promotes what is sometimes called "unobtrusive javascript", as well as graceful degradation of your application. The idea of graceful degradation (or "progressive enhancement") is that you make the link a real link that would go to a separate page, but then you use javascript to hijack the click event, and provide the same functionality without leaving the page. This way, if the user doesn't have javascript (say they are a disabled user using a screen reader) the application still works.

  3. It makes the javascript more reusable; say I define the element to bind my event handler to based on something generic such as a CSS class. Then I can drop that javascript onto a variety of pages and have it "just work". I do this all the time for things like autosave, for example.

不回头走下去 2024-09-14 15:43:50

我知道您的担忧,因为我也有类似的担忧,并决定使用 Jquery 和命名空间来绑定来自 javascript 命名空间的事件。这就是我如何将事件挂钩到单个元素以及将事件挂钩到具有相同类或标记名的多个元素。

基本上,我对单击、悬停、鼠标悬停等事件进行了命名空间,然后在 document.ready 中调用命名空间事件。原因是我可以从一个地方查看所有点击、悬停、鼠标悬停事件。

<script type="text/javascript">

  var Page1 = {
    Events: {
       click: {
         elementid: {
           func: function(evt) {  //where elementname is the id of your element
           //your code here
           },
           selector: "#someId"
         }
         elementclass: {
           func: function(evt) { //where elementclass is the class of your element(s)
           //your code here
           },
           selector: ".someClass"
         },
       mouseover: {
         //similar to click namespace
       },
       mouseout: {
         //similar to click namespace
       },
       ....
    }
  };

  $(document).ready(function() {
    for (var key in Page1.Events) {
      for (var eventKey in Page1.Events[key]) {
        $(Page1.Events[key][eventKey].selector).bind(key, Page1.Events[key][eventKey].func);
      }
    }
  });

</script>

现在,这样做的好处是您只需将事件添加到命名空间,它们就会自动与文档就绪挂钩。您还可以用 Live 或 delegate 替换 $.bind 调用以挂钩未来的 dom 元素。

I know your concern because I had a similar concern and decided to use Jquery and namespacing to bind events from a javascript namespace. This is how I worked around hooking events to a single element as well as hooking events to multiple elements with the same class or tagname.

Basically I namespaced my click, hover, mouseover, etc... events and then call the namespaced events in my document.ready. The reason for this is I can look at all my click, hover, mouseover events from one place.

<script type="text/javascript">

  var Page1 = {
    Events: {
       click: {
         elementid: {
           func: function(evt) {  //where elementname is the id of your element
           //your code here
           },
           selector: "#someId"
         }
         elementclass: {
           func: function(evt) { //where elementclass is the class of your element(s)
           //your code here
           },
           selector: ".someClass"
         },
       mouseover: {
         //similar to click namespace
       },
       mouseout: {
         //similar to click namespace
       },
       ....
    }
  };

  $(document).ready(function() {
    for (var key in Page1.Events) {
      for (var eventKey in Page1.Events[key]) {
        $(Page1.Events[key][eventKey].selector).bind(key, Page1.Events[key][eventKey].func);
      }
    }
  });

</script>

Now the nice thing about this is you simply add events to your namespace and they will automatically get hooked on document ready. you could also replace the $.bind call with Live or delegate to hook to future dom elements.

笔落惊风雨 2024-09-14 15:43:50

JQuery 处理事件的方式被定义为不引人注目 (http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) 并且通常优于“标准”方式,因为逻辑和表示之间有明确的分离,并且通常代码更可重用。

更不用说 JQuery(但其他库也做同样的事情)为您处理浏览器不一致问题。

JQuery's way of handling events is defined unobtrusive (http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) and is usually preferred over the "standard" way because you have a clear separation between logic and presentation, and generally code is more reusable.

Not to mention that JQuery (but other libraries does the same thing too) handle browser inconsistencies for you.

莫言歌 2024-09-14 15:43:50

恕我直言,我不喜欢用 jQuery 方法阅读 html 时,不知道链接的作用。

禁用 JavaScript 的浏览器也不知道您的链接的作用。他们看到一个指向文档顶部的链接!

其他答案已经给了您很多避免 HTML 中 onclick 样式事件的理由...我也尽力避免 HTML 中的链接,确保文档中的任何 标记都有其用途。我经常使用 jQuery 创建额外的 标签来添加功能仅当浏览器允许我处理它们上的点击事件

Imho I don't like that when reading the html with the jQuery method, there's no clue as to what the link does.

The browser with JavaScript disabled has no clue what your link does either. They see a link pointing them to the top of the document!

Other answers already give you a number of reasons to avoid onclick style events in your HTML... I also try my best to avoid <a href="#"> links in my HTML, ensuring that any <a> tags in the document have a purpose. I will often use jQuery to create extra <a> tags to add the functionality only if the browser will let me handle the click events on them

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