Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Xử lý sự kiện Trong nhiều kịch bản, đó là mong muốn có hành động nào đó xảy ra khi các sự kiện, hoặc các hành động trình duyệt, xảy ra. Hỗ trợ được xây dựng vào jQuery để xử lý các sự kiện trình duyệt, mà bạn sẽ học trong phần này. | CHAPTER 2 COMMON JQUERY ACTIONS AND METHODS duration 6000 step function if count 200 this .stop true true Handling Events In many scripts it s desirable to have certain actions occur when certain events or browser actions occur. Support is built into jQuery to handle browser events which you ll learn in this section. Browser Events Browser events occur when the browser itself experiences a change or error. .errorO If a browser error occurs this event is triggered. One common instance of a browser error would be an image tag that tries to load an image that does not exist. The .error method allows developers to bind a handler i.e. a function to be fired if the event occurs to the event. Create an image tag that tries to display an image that doesn t exist and attach an error handler to the error event that outputs a message to the console img src not an image.png alt This image does not exist .error function console.log The image cannot be loaded .appendTo body Upon execution of this code the console will display the following 71 CHAPTER 2 COMMON JQUERY ACTIONS AND METHODS img src not an image.png .ot be loaded .appendTo body img image.png The image cannot be loaded .scrollO If the document is scrolled the scroll event is fired. To bind a handler to this event use the .scroll method window .scroll function console.log The window was scrolled After executing this code scrolling the browser window will cause a message to be logged in the console. Additionally calling the .scroll method without any parameters will trigger the scroll event to fire. After binding the preceding handler to the window trigger the event by running the following window .scroll Executing this code will log the scroll event handler s message in the console. Handling Document Loading Events Often JavaScript needs to wait until the document is ready before executing any scripts. Also when users exit a page sometimes it s desirable to fire a function to ensure they meant to navigate away from it.