Add jQuery colorbox plugin to a dynamically create

2019-01-23 04:41发布

The usual way to assign color box functionality on a link is like this:

$("a.colorbox").colorbox({ transition: "elastic" });

Newly added items are not bound in this way though.

How can I add colorbox to dynamically created

<a class="colorbox"></a>
elements too?

6条回答
男人必须洒脱
2楼-- · 2019-01-23 05:17

This post is old but this may help others: simonthetwit solution is ok, but you'll need to click the trigger link twice. Colorbox can be called directly, so this should work:

$( '.colorbox' ).live('click',function(e){
        e.preventDefault();
        $.colorbox({open:true});
        //inline example
        //$.colorbox({inline:true, width:"50%", href:"#inline_content"});
});

Cheers!

查看更多
Explosion°爆炸
3楼-- · 2019-01-23 05:20

You could also try this:

$('.colorbox').live('click',function(e){
    e.preventDefault();
    $(this).colorbox({open:true});
});

I think it's a little cleaner then using the fn command.

查看更多
淡お忘
4楼-- · 2019-01-23 05:24

As live is depreciated, you should use on

$('body').on('click', '.colorbox', function() {
    $('.colorbox').colorbox({rel: $(this).attr('rel')});
});

This code also allows grouping.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-23 05:33

The method described here is to live-bind to the click event on the elements you're interested in (such as .colorbox in this instance) and call the colorbox library function in the handler:

$('.colorbox').live('click', function() {
  $.colorbox({href:$(this).attr('href'), open:true});
  return false;
});
查看更多
虎瘦雄心在
6楼-- · 2019-01-23 05:33

I was having the same problem as @sunburst with having to click the trigger link twice. Used the same code, but .delegate() instead of .live(). Solved everything and cleaned up my jQuery nicely!

Nice explanation here: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

查看更多
等我变得足够好
7楼-- · 2019-01-23 05:34

Here was the solution I found to avoid the needing of clicking twice the link to fire the event:

$(document.body).delegate('.<my-class>', 'click', function(e) {  
    e.preventDefault();  
    $('.<my-class>').colorbox({<my-code>})  
});
查看更多
登录 后发表回答