Fancybox-是否可以使用javascript变量字符串作为HTML内容

Fancybox - is it possible to use a javascript variable string as the HTML content?

本文关键字:HTML 内容 字符串 变量 是否 可以使 javascript Fancybox-      更新时间:2023-09-26

我知道Fancybox的说明表明,内容可以通过四种方式中的任何一种传递;图像、内联、iFrame或Ajax。

然而,我想知道我是否有这样的字符串:

var html = "<p>Some html content</p>";

如果我可以使用这些内容调用一个fancybox窗口?

EDIT关于JFK下面的回答,根据条件提供内容的最佳方式是什么?例如,假设我有两个不同的fancybox链接:

<a href="#" class="fancybox class-one">Click me</a>
<a href="#" class="fancybox class-two">Click me</a>

所以,当点击任一链接时,我想根据第二个类名显示不同的内容?

是的,这是可能的。您也可以将html设置为contenttype,这样就可以工作了

var html = "<p>Some html content</p>";
jQuery(document).ready(function ($) {
    $(".fancybox").fancybox({
        type: "html", // not an image but html
        content: html // overrides fancybox content
    });
}); // ready

请注意API选项content会覆盖扇盒content,而不管绑定到扇盒的锚的href属性中设置了什么,因此此

<a class="fancybox" href="images/01.jpg">Open Fancybox</a>

仍将在fancybox中显示javascript变量的值,而不是在href 中显示图像

请参阅JSFIDDLE


编辑

根据中选择器的提供内容

<a href="#" class="fancybox class-one">Click me</a>
<a href="#" class="fancybox class-two">Click me</a>

我认为最好使用switch语句(在.on()方法中)来动态设置html变量的值。然后以编程方式启动fancybox,如:

var html; // initialize variable globally
jQuery(document).ready(function ($) {
    $(".fancybox").on("click", function () {
        switch (this.className) {
            case "fancybox class-one":
                html = "<p>Some html content for class-one</p>";
                break;
            case "fancybox class-two":
                html = "<p>And this the html content for class-two</p>";
                break;
            default:
                html = "<p>html default content</p>";
        };
        $.fancybox({
            type: "html",
            content: html
        });
        return false; 
    });
}); // ready

请参阅分叉JSFIDDLE