Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - activate lightbox on dynamically added content

I'm developing a little portfolio where I can choose a category and when I click it, the content (thumbnails) of that category will be shown (this is via an array).

e.g.

photography[0] = <a href="..." rel="lightbox" /><img ...  /></a>
photography[1] = <a href="..." rel="lightbox" /><img ...  /></a>

At first the site shows the content of all categories and when I click a thumbnail it activates lightbox, however if I choose a category and then press one of the remaining thumbnails is simply leads to the image and does not open the image with lightbox.

This is how the thumbnails look like on the initial load of the page:

<div><a title="..." rel="lightbox" href="http://...yellow-brick-road.jpg" class="thumbnaila"> <img class="thumbnail " alt="" src="http://...yellow-brick-road.jpg" /></a>

When a category is selected it removes the content within the div and replaces it by other content e.g. exactly the same content. (so the rel="lightbox" is still there).

If anyone could help me out with this one I would love it (I'm using jquery btw).

EDIT after response Alex Sexton:

$(".thumbnaila").live("mouseover", function(){
    activateLightbox($(this));});

function activateLightbox(dit) {
    $('a[rel="lightbox"]').lightBox({
            overlayBgColor: '#000',
            overlayOpacity: 0.65,
            containerResizeSpeed: 350
    });

}

but now when I choose a categorie and select a thumbnail it loads the right lightbox but also loads an empty lightbox above the one I want as you can see:

enter image description here

Anyone know what's causing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are binding the links with a regular event handler:

$('a[rel=lightbox]').click(function(e){ ... });

Then any new content that is added after the bind won't be captured.

You can either rerun the bind when you change out the content, or more simply use jQuery's event delegation to attach the handler:

$('a[rel=lightbox]').live('click', function(e){ ... });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...