Details about jQuery dynamic append page data and event Delegation

Source: Internet
Author: User

Details about jQuery dynamic append page data and event Delegation

The task we want to perform is to have some images at the beginning of the page. We have a More Photos link under it. Click it, load some images to the current page, and then click the link, continue loading until the page we listed is loaded, and the link disappears.

The first step is as follows:

This only captures the bottom part of the page. When you move the cursor over an image, text appears. When you move the cursor out of the image, the text disappears.
What we need to do now is to load part of the data when we click the MorePhotos Link under it, and then click load part of the data until the data is loaded.
First, the code in the body is as follows:

<Div id = "container"> 

Then, write several HTML code snippets in the same root directory for loading.

For example, I have a 1.html Code as follows:

<div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>  <div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>    <div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>    <div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>    <div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>    <div class = "photo">        <div class = "details">      <div class = "description">The Cullin Mountains, Isle of skye </div>      <div class = "date">12/24/2000</div>      <div class = "photographer"> Alasdair Dougall</div>    </div>  </div>

In this HTML clip, I introduced 6 images. Other segments such as 2.html can be written in the same way as above. After defining many HTML fragments, use jQuery to dynamically append data.

First introduce a jquery library http://libs.baidu.com/jquery/1.9.0/jquery.js

<Script> $ (document ). ready (function () {// define a variable to record the current page var pageNum = 1; // Add a click event to the link $ ("# more-photos "). click (function (event) {event. preventDefault (); var $ link = $ (this); // obtain the url var url of the current link = $ link. attr ('href '); // if the url of the link exists, append the page if (url) {$. get (url, function (data) {$ ("# gallery "). append (data) ;}); pageNum ++; // There are a total of 10 segments to be added. The names are separated into 1.html, 2.html ...10.html. When the total number of current pages is less than the total number, link updates are performed. If (pageNum <10) {$ link. attr ('href ','./'?pagenum='.html ');} // when all fragments are appended, remove the link. Else {$ link. remove ();}}})});

The above code can dynamically append data to the page.

However, the following error occurs in Google's browser:

Jquery. js: 8475 XMLHttpRequest cannot load file: // C: /Users/% E9 % 95% BF % E5 % AD % 99% E4 % B8 % B9 % E5 % 87% A4/Desktop/webtest/1.html. cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

It is okay to test in IE10 environment.

SolutionYou just need to install a web server, copy the file to the project, and access the file by path on the web server! Such as http: // localhost: 8080/ajax/ajaxLoad.html

As there are also mouse suspension events, when we move the mouse over an image, the text will appear. When we move the mouse out, the text on the image will disappear.

$(document).ready(function(){    $('div .photo').hover(function(){      $(this).find('.details').fadeTo('slow', 0.7);    },function(){        $(this).find('.details').fadeOut('slow');    })  });

Alternatively, you can combine the above Code to reduce redundant code:

$ (Document ). ready (function () {$ ('div. photo '). on ('mouseenter mouseleave ', function (event) {var $ details = $ (this ). find ('. details '); if (event. type = 'mouseenter') {$ details. fadeTo ('low', 0.7); // 0.7 indicates transparency} else {$ details. fadeOut ('low ');}})});

When we use the above two types of code to add a hover event for each image, only those images on the initial page will be bound to events, however, events cannot be bound to images Dynamically Loaded. Because the event handler will only be added to elements that already exist when the method is called, such as the dynamically appended elements, will not be bound to those events.

There are two solutions:

1. rebind the event handler after Dynamic Loading
2. From the very beginning, events are bound to existing elements and dependent on Event bubbles.

The next step is to use the jquery delegate method;

$(document).ready(function(){    $('#gallery').on('mouseenter mouseleave', 'div.photo', function(event){      var $details = $(this).find('.details');      if(event.type == 'mouseenter'){        $details.fadeTo('slow', 0.7);      }      else{        $details.fadeOut('slow');      }    })  })

$ ('# Gallery '). on ('mouseenter mouseleave ', 'div. in photo ', function (event. photo' is used as the second parameter ,. the on () method maps this to the elements that match the selector in gallery. In other words, this is the element that points to div class = 'photo' in gallery.

Therefore, in the last append page, because all elements belong to the gallery, corresponding events are added to each image.

If you do not know the parent element of the page to be added, replace '# gallery' in $ ('# gallery'). on () with document. In this way, you do not have to worry about selecting the wrong container. Because document is the ancestor of all elements on the page.

However, document has the following drawbacks:

When the DOM nested structure is deep, event bubbling may cause a great performance loss through a large number of ancestor elements.
However, there are other reasons for us to select document as the delegate scope.
Generally, an event handler is bound to a DOM element only after it is loaded. This is why we need to put the code inside $ (document). ready (function. However, the document element can be called almost immediately as the page is loaded. Bind the handler to the document without waiting until the complete DOM build ends. The code above can be written :'

(function($){    $(document).on('mouseenter mouseleave', 'div.photo', function(event){      var $details = $(this).find('.details');      if(event.type == 'mouseenter'){        $details.fadeTo('slow', 0.7);      }      else{        $details.fadeOut('slow');      }    })  })(jQuery);

Because the entire document is not ready, you can ensure that all <div class = 'photo'> elements can apply the mouseenter and mouseleave actions as long as they are displayed on the page.

The above is all about using jQuery to dynamically append page data and event delegation. The source code is attached below;

<! DOCTYPE html> 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.