Fancybox, getting Fancybox to bind using LIVE() to items being loaded onto the page after load

百般思念 提交于 2019-12-17 10:49:17

问题


I have a page that loads and after it loads, it pulls in a list of LIs to populate a news feed.

<li><a href="/url/" class="quickview">quick view</a></li>
<li><a href="/url/" class="quickview">quick view</a></li>
<li><a href="/url/" class="quickview">quick view</a></li>

I'm trying to get fancy box to trigger when a user clicks on quick view but haven't had any luck. Any Ideas?

$(document).ready(function() {
    $('.quickview').fancybox();
});

also tried:

$(document).ready(function() {
   $('a.quickview').live('click', function() {
        $(this).fancybox();
    });
});

http://fancybox.net/

Thanks for any ideas...


回答1:


The problems is to attach fancybox into AJAX loaded element, right?

I got same problems and I found this solution.

I copy paste it here, see the original bug report for more info:

$.fn.fancybox = function(options) {

$(this)
  .die('click.fb')
  .live('click.fb', function(e) {       
    $(this).data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
    e.preventDefault();
    [...]

Credit goes to jeff.gran.




回答2:


Old question, but might be useful for future searchers.

My preferred solution is to fire fancybox manually from within the live event, eg:

$('.lightbox').live('click', function() {
    $this = $(this);
    $.fancybox({
        height: '100%',
        href: $this.attr('href'),
        type: 'iframe',
        width: '100%'
    });
    return false;
});

EDIT: From jQuery 1.7 live() is deprecated and on() should be used instead. See http://api.jquery.com/live/ for more info.




回答3:


this should work after every ajax request

$(document).ajaxStop(function() { 
    $("#whatever").fancybox();
});



回答4:


Since .on is now recommended over .live, and after reading over the documentation on delegated events, here's a solution I came up with (assuming your elements have a class of 'trigger-modal'):

$(document).on('click', '.trigger-modal', function() {
  // remove the class to ensure this will only run once
  $(this).removeClass('trigger-modal');
  // now attach fancybox and click to open it
  $(this).fancybox().click();
  // prevent default action
  return false;
});



回答5:


From my understanding of Fancybox, the call to fancybox() simple attaches the plugin to the selected element. Calling fancybox on a click event won't open anything.

I think you just need to add

$(li_element_that_you_create).fancybox();

to the code that creates the new LI elements in your list

EDIT

If you're using load, then you would do something like:

$('#ul_id_goes_here').load('source/of/news.feed', function() {
  $('.quickview').fancybox();
});


来源:https://stackoverflow.com/questions/2532070/fancybox-getting-fancybox-to-bind-using-live-to-items-being-loaded-onto-the-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!