colorbox与元素实时绑定'分组获胜'不起作用

colorbox bind on live with elements' grouping won't work

本文关键字:获胜 不起作用 绑定 colorbox 元素 实时      更新时间:2023-09-26

我正在使用众所周知的优秀jQuery Colorbox作为库。使用ajax将部分图像添加到页面中。我正在尝试将colorbox绑定到页面上所有新的和现有的图像,并将所有图像组合在一起。现在,我只成功地实现了这两个目标中的一个。使用此代码,所有图像都可以很好地分组到一个colorbox库中,但在向页面添加更多图像(通过ajax)后,colorbox根本不会绑定到它们:

$('a.exhibition').colorbox({
    inline:true,
    href:$(this).attr('href'),
    opacity:0.5, 
    overlayClose:true, 
    rel:"hpexhibition"
});

使用此代码,在向页面添加更多图像后,图像将绑定到颜色框,但rel分组不起作用(甚至不适用于最初加载到页面的图像集):

$('a.exhibition').live('click', function() {
    $.fn.colorbox({
        inline:true,
        href:$(this).attr('href'),
        opacity:0.5, 
        overlayClose:true,      
        rel:"hpexhibition"
    });
    return false;
});

我也尝试过这个代码,但它是一样的-图像很好地绑定到了colorbox,但作为单个图像,而不是作为(rel)库:

$("ul#home-exhibition").on("click", "a[rel='hpexhibition']", function (event) {
    event.preventDefault();
        $.colorbox({
            inline:true,
        href:$(this).attr('href'),
        opacity:0.5, 
        overlayClose:true, 
        rel:"hpexhibition"                
         });
});

我的图片库html标记是这样的:

<ul id="home-exhibition">       
    <li class="item">
        <a class="exhibition" rel="hpexhibition" ref="3" href="#artitem-cb-details-3">
            <img src="path/to/image53.jpg" alt="" />
        </a>
        <div style="display:none;">
           <div id="artitem-cb-details-3" class="artitem-cb">
            //Some data of image 3 here...
          </div>    
        </div>
    </li>
    <li class="item">
        <a class="exhibition" rel="hpexhibition" ref="4" href="#artitem-cb-details-4">
            <img src="path/to/image4.jpg" alt="" />
        </a>
        <div style="display:none;">
           <div id="artitem-cb-details-4" class="artitem-cb">
            //Some data of image 4 here...
          </div>    
        </div>
    </li>
    <li> ..... </li>
    <li> ..... </li>
    <li> ..... </li>
</ul>

有没有一种方法可以将这两者结合起来,使colorbox适用于页面上的所有图像——也适用于通过ajax添加的图像——并将所有图像分组在一起?我做不到。我相信应该有办法让它发挥作用。

可能有效的方法需要在加载新元素后重新初始化颜色框。

换句话说,你必须做:

$('a.exhibition').colorbox({
    inline:true,
    href:$(this).attr('href'),
    opacity:0.5, 
    overlayClose:true, 
    rel:"hpexhibition"
});

ajax调用完成后。

看看colorbox的代码,我看不出其他简单的方法来处理你的案件。

将this而不是$('.colorbox').colorbox();

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

我的解决方案

  // This is the trick. Initialize but don't open
  $('.colorbox').colorbox({open:false, rel:'gallery'});
  // Handle click event    
  $('.colorbox').live('click',function(e){
     $(this).colorbox({open:true, rel:'gallery'}); // now open colorbox
     return false;
  });