JQuery: Why Unobtrusive JavaScript / Document Ready function rather than OnClick event?

前端 未结 4 918
别那么骄傲
别那么骄傲 2020-12-15 01:26

I\'ve just started looking at JQuery. I don\'t have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

4条回答
  •  难免孤独
    2020-12-15 01:47

    Unobtrusive JavaScript is the main driver for separating JS code from markup

    • Separation of functionality (the "behavior layer") from a Web page's
      structure/content and presentation
    • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
    • Progressive enhancement to support user agents that may not support
      advanced JavaScript functionality

    With the code in document.ready, it will not execute until the DOM has loaded and before the page contents are loaded

    From Learning jQuery

    With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

    You may want to take a look at jQuery in Action, I'd highly recommend it. You can sample Chapter 1 and Chapter 5 on the book's homepage. I think doing so may provide further insight into why separation can work well.

    Finally, have a look at this question which has answers that detail how you would find the event listeners on a DOM node.

    EDIT:

    Some thoughts which may persuade you why unobtrusive JavaScript can be a good idea.

    Imagine that you have a function bound as an event handler for the same event raised on each of a number of elements -

    • Would it be easier to find out which elements call that function to handle an event when the declaration is inline in each element, or the declaration is in one place, outside of the markup?

    • What if you want to add to the elements that call that function when the event is raised on each of them? Would it be easier/better to add the event handler inline to each element or to change the code in one place?

提交回复
热议问题