The difference between on and click in jQuery

【Foreword】

     In development, we sometimes encounter scenarios where click events fail. I have summarized them before, and encountered them again today. So I will record it here and mention it later in the lecture.

      Question: Difference between on and click in jQuery

      It is recommended to use the on method in development

【main body】

   $().click() and $(document).on('click', 'the element to be selected', function(){}) are both click event operations, but there are also differences.

 

  1. $(selector).click(fn)

    The callback function fn is fired when the selected selector is clicked. Only for selectors that already exist on the page.

 

  2. $(document).on('click', 'element to be selected', function(){})

    The on method contains many events, click, double click and so on. Like the usage of $().click(), the biggest difference is that the advantage is that if the dynamically created element is within the selection range of the selector, the callback function can be triggered.

 

【Summarize】

      click is a click event, but after the page is loaded, the newly added element of the jquery event cannot be obtained with click. At this time, you need to use on to obtain the element event. Simply put, the element displayed on the page when the page is loaded can be Use on, you can also use click, but the elements that are added later after the page is loaded can only be used on.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326081736&siteId=291194637