灯箱2:如何通过javascript动态添加图片 [英] lightbox 2: how to add dynamically images via javascript

查看:99
本文介绍了灯箱2:如何通过javascript动态添加图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试动态添加图像时遇到了麻烦,因为 lightbox2 (由lokesh dakar编写)是在文档加载后由现有的html编码图像初始化的,并且没有第一次之后就不再解析文档.

I'm having trouble attempting to dynamically add images, since lightbox2 (by lokesh dakar) is initialized after document load by existent html coded images and it doesn't parse the document anymore after the first time.

如果我尝试使用javascript添加新图像(例如,将其添加到正文中),则不会将其添加到lighbox组中.

If i try to add new images with javascript (appending them in the body for example) they are not added to the lighbox groups.

官方网站上的文档似乎没有描述任何脚本化方法

Documentation in official website doesn't seems to describe any scripted method

任何有经验的人都可以帮助我吗?确实欢迎使用 jquery 解决方案,但我也可以很好地处理 vanilla js.

Anyone with experience can help me? solution with jquery are really welcome, but i can handle well vanilla js too.

代码示例:

HTML

<body>
 <div id="container">
  <a href="images/image-2.jpg" data-lightbox="roadtrip">Image #2</a>
  <a href="images/image-3.jpg" data-lightbox="roadtrip">Image #3</a>
  <a href="images/image-4.jpg" data-lightbox="roadtrip">Image #4</a>
 </div>
 <!-- where 'Image #X' = <img src="images/thumb/image-X.jpg>" -->
 <div id="loadmore">load more images</div>
 <script src="path/to/lightbox.js"></script>
 <script>
  /* see below for the script */
 </script>
</body>

javascript

$(function(){
  $('#loadmore').click(function(){
   //ajax request for more images.
   //load them with all the needed properties...
   //then put them into the container:
   var IMG = $('<a href="images/image-10.jpg" data-lightbox="roadtrip">'+
       '<img src="images/small/image-10.jpg">'+
     '</a>');
   //magic here... add IMG to roadtrip lightbox group!!!
   //probably something like lightbox.groups['roadtrip'].add(IMG)
   //but i'm only speculating
   $('#container').append(IMG)
  });
})

推荐答案

在花了几个小时测试和阅读代码之后,我想到了这个神奇的代码:

After a couple of hours spent on testing and reading the code, I came up with this magic code:

//set album values
IMG = $('<a href="...">')
    .attr('data-lightbox','roadtrip')
    .append('<img src="...">')
//lightbox open:
IMG.click(function(){
    lightbox.start($(this));
    return false;
})

一些有用的提示:

  • 请勿使用$(...).data('lightbox','group')设置数据,因为每次单击链接时,lightbox都会使用选择器$('a[data-lightbox]').相反,您应该使用$(...).attr('lightbox','group').

  • don't set data with $(...).data('lightbox','group'), since lightbox uses the selector $('a[data-lightbox]') each time a link is clicked. Instead, you should use $(...).attr('lightbox','group').

lightbox.album是一个不需要处理的临时变量.

lightbox.album is a temporary variable which you don't need to deal with.

这篇关于灯箱2:如何通过javascript动态添加图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆