0

单击链接后,我在我的网站上使用 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 页面?

4

1 回答 1

2

我能想到几种可能性。

一种是使用 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 调用受同源策略的约束

于 2013-08-13T16:16:55.257 回答