JS for DOM element binding event notes

Source: Internet
Author: User

The bound event for a DOM element that is loaded asynchronously must be bound after the load is complete:

$ (' body '). Load (' learnclickbinding.ashx ');
$ (' a '). Click (function () {alert (' I was clicked! ');});

The above binding is invalid because asynchronous loading takes time, and $ (' a ') is already executed before the element is fetched. Click (); method, so the binding fails.

The right thing to do is to wait for the element to finish loading and then execute $ (' a '). Click ();

$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');});

});

  

JS for DOM element binding events can only be valid until the page is refreshed, that is, before the DOM element is reloaded. This problem is especially true when loading DOM elements asynchronously.

$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');}); $ (' body '). empty (); $ ("<a href= ' # ' >click me!</a>"). AppendTo (' body ');});

This binding is also a failure because the a element of the binding event has been empty, and the A element behind append is no event, so the click button still has no effect.

The correct binding method:

$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');}); $ (' body '). empty (); $ ("<a href= ' # ' >click me!</a>"). AppendTo (' body '), $ (' a '). Click (function () {alert (' I was clicked! ');});

  

JS for DOM element binding event notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.