简体   繁体   中英

How to make a function repeat/loop in jQuery?

I have a function here for centering an element within it's parent. Check out the demo: http://jsfiddle.net/kE9xW/1/

right now it's only applying the centering to the first element, how do i make the function loop itself so it centers every #element on the page. the demo is self explanatory, thanks!

First, the easiest but most important part: change your IDs to classes. IDs must be unique per page so jQuery's ID selector and JavaScript's document.getElementById() function are only going to give you the first matching element:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.

Change

<div id="container">
    ...
    <div id="element">

to

<div class="container">
    ...
    <div class="element">

and change

$('#element')

to

$('.element')

Next, the more difficult part: you are currently issuing one centerDiv() call to your elements with coordinates from center of 0, 0 . That's going to take all your .element s and position them at the exact same spot.

If that's not what you intend, you're going to have to loop through them using .each() and decide the xPosFromCenter and yPosFromCenter in each iteration. It's not clear to me yet how your function works so you may have to explore on your own and see what you can come up with.

Scratch that, see Jamiec's working example for the solution.

There are a few things you need to do.

  1. As already suggested, id's must be unique, so change the id="..." to class="...". You will also need to change your css to be based on the class not the id (change #element' to '.element')

     <div class="container"> <p> ... </p> <div class="element"> &nbsp; </div> </div> 
  2. Use each in your method to loop over all elements selected by the selector $('.element') .

     element.each(function(){ // work here in $(this) for the current element }); 
  3. You forgot to take the top of the parent div into account, which made all elements overlap each other. So your yPas becomes:

     var yPos = $(this).parent().position().top + parseInt($(this).parent().css('height'))/2 - parseInt($(this).css('height'))/2 - yPosFromCenter; 

Check the working fiddle: http://jsfiddle.net/H99DT/

Change Id to class in you divs, then make container's position relative with css, and I'll suggest make jQuery plugin from your function. See results http://jsfiddle.net/kE9xW/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM