【问题标题】:Open a fancybox link with ajax用ajax打开一个fancybox链接
【发布时间】:2013-08-13 08:55:01
【问题描述】:

我在我的网站上使用 Fancybox 在您单击链接后显示一些内容。我用于此的代码:

JS 中:

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

打开 Fancybox 窗口的链接:

<a rel="nofollow" target="_blank" class="fancybox" href="#show_code_8">Show code</a>

在 Fanctbox 窗口中打开的代码(只是一个示例):

<div id="show_code_8" class="inline">
  Some content here
</div>

它工作正常,但我想通过 ajax 加载内容而不是这个。我尝试了很多,但无法使其正常工作。我已经设法通过 ajax 打开了 ajax 页面,但那是没有正确的 ID(来自 href="#show_code_8" 的 8 变量)。有人可以告诉我如何使用正确的 ID 打开 Ajax 页面吗?如何将变量传递给 ajax 页面?

【问题讨论】:

    标签: jquery ajax fancybox fancybox-2


    【解决方案1】:

    我能想到几种可能性。

    一个是使用 php 文件,当您使用诸如

    <a class="fancybox" href="allCodeContent.php?code=show_code_8" ...
    

    另一个仅使用 jQuery 的方法是使用 .load().html 文件中调用特定代码(部分)

    例如,一个名为allCodeContent.html 的文件可能有这样的内容:

    <div id="show_code_1">This is code one</div>
    <div id="show_code_2">This is code two</div>
    <div id="show_code_3">This is code three</div>
    <div id="show_code_4">This is code four</div>
    ... etc
    

    然后,您调用主页中的每个代码部分,例如:

    <a class="fancybox" href="#show_code_1">show code one in fancybox</a>
    <a class="fancybox" href="#show_code_2">show code two in fancybox</a>
    <a class="fancybox" href="#show_code_3">show code three in fancybox</a>
    <a class="fancybox" href="#show_code_4">show code four in fancybox</a>
    ...etc.
    

    您可能需要创建一个占位符容器(在您的主页中)以每次加载代码部分

    <div id="ajaxContentPlaceholder" style="display:none;"></div>
    

    然后使用这个脚本:

    jQuery(function($) {
        $(".fancybox").on("click", function(){
            var $code = this.href.split("#");
            $("#ajaxContentPlaceholder").load("allCodeContent.html #"+$code[1], function(){
                $.fancybox(this);
            });
            return false;
        }); // on
    }); // ready
    

    请记住,ajax 调用受same origin policy 的约束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多