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

Categories

0 votes
1.3k 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 Reply

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){ ... });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...