I have the following list
<di开发者_如何学Gov id="imgrt">
<ul id="if">
<li><img src="../pictures/album/20-c-44.jpg" /></li>
<li><img src="../pictures/album/21-c-44.jpg" /></li>
<li><img src="../pictures/album/u1-c-44.jpg" /></li>
</ul>
</div>
I have a button which which on click is going to animate by pushing each image to the left margin. What i sort of did was was
function animateImages(iD, index) {
var j = passedIndex;
iD.children().each(function(index){
if (passedIndex == index)
jquery(this).animate(.........);
return (index+1);
});
}
var nextIndex = 0;
jquery('#next').click(function() {
nextIndex = animateImages(jquery('#li',nextIndex);
});
My question
- if you notice this is kind of bad implementation (atleast am guessing so, please correct if wrong), i'm doing a function call to animateImages which does nothing but just querying a jquery(this) element in the list and breaking after animating. How can i do it efficiently?
Thanks in advance.
[Addition Notes] - just noticed the last part of jquery.each() where they have mentioned to exit early. Basically i want to exit early in the loop but the early is after every iteration. So it will be like return (somthing)
Please suggest some better ways for this. As mentioned above, when i click a button, the control will jump to the animateImages function which will navigate through the element in the list, animate the image and return the index in the list. On next click, it will go to the same list, and check for the index, and if index matches the list element, animate it and return the new index and so on.
I've modified it slightly so that the current image has an id:
<div id="imgrt">
<ul id="if">
<li id="current"><img src="../pictures/album/20-c-44.jpg" /></li>
<li><img src="../pictures/album/21-c-44.jpg" /></li>
<li><img src="../pictures/album/u1-c-44.jpg" /></li>
</ul>
</div>
<a href="#" id="next">Next</a>
This way your javascript can look like this:
$('#next').click(function(e){
e.preventDefault();
e.stopPropagation();
var $current = $('#current');
$('#current').next().attr('id','temp-curr');
// animation code
$current.removeAttr('id');
$('#temp-curr').attr('id','current');
});
The reason I did it this way is so that only ONE element ever has the #current id, this way if any of your other code ties in to it, it won't get confused if it ever runs when there are two elements named current.
I would add your animate code and tie it in to sliding the entire ul element. instead of looping through your entire list every time. Just set a width on the #imgrt and set overflow to hidden.
精彩评论