jQuery storing and referring to an array of items
I'm not exactly what I'm looking for in jQuery/Javascript terms. The behavior I'm looking for is akin to your typical lightbox slide show with the following elements:
- a list of items
- clicking on an item will bring up a new element that references the item in the list
- while the new element includes next/prev navigation that refers back to the list of items.
I'm building something like that and am looking for the technical approach for handling the above.
I have this for sample code:
<ul>
<li><a href="samplelink.html">item 1</a></li>
<li><a href="anotherlink.html">item 2</a></li>
<li><a href="onemorelink.h开发者_高级运维tml">item 3</a></li>
</ul>
I have things set up so that each LI A gets a click event that creates a new overlay DIV on the page, then does a .load($(this).attr('href)) into it.
All that works great.
What I don't know how to do is, pass which index of LI I clicked on to the new div so I can add the proper prev/next links and actually refer to the next/prev element in the original list. Specific example, if I click on the second list item, in the new DIV I create, how do I pass into it the information that "it was the second link that opened this".
In your div code you can select your item again matching on passed href value and use next() and prev() to get the other siblings for given element.
Try this:
<ul>
<li><a href="1">item 1</a></li>
<li><a href="2">item 2</a></li>
<li><a href="3">item 3</a></li>
</ul>
<a id="next">next</a>
<a id="prev">prev</a>
<script>
$('ul').bind('click', function(e) {
var target = $(e.target);
if (!target.is('a')) {
return;
}
var li = target.parent();
console.log('opening: '+target.attr('href'));
var next = li.is(':last-child') ? li.siblings(':first') : li.next();
var prev = li.is(':first-child') ? li.siblings(':last') : li.prev();
$('#next').unbind('click').bind('click', function(e) {
next.children('a').trigger('click');
})
$('#prev').unbind('click').bind('click', function(e) {
prev.children('a').trigger('click');
})
e.preventDefault();
})
</script>
When you create the div
use the jQuery data
feature to basically "link" the two DOM elements:
$("ul li a").click(function(e){
var $this = $(this);
$("<div class='overlay'></div>")
.data('trigger', $this)
.appendTo(body)
.load($this.attr('href'));
e.preventDefault();
});
Then you can just use a .live
event to capture clicks for next
and previous
in your overlay divs
:
$("div.overlay a.next").live('click', function(e){
var $div = $(this).closest('div.overlay'),
$trigger = $div.data('trigger'),
$next = $trigger.parent().next();
if($next.length){
// It got the next li
// $next.find('a') would select the link
} else {
// It reached the end
$next = $("ul li:first"); // Grab first now
// $next.find('a') would select the link
}
});
Write pretty much the opposite for prev
.
精彩评论