简体   繁体   中英

Getting only first database entry with Fancybox

I have a while loop that gets the images from my database. if you click on the image, a box pops up with the corresponding name.

So if the image of an ape is connected to the text "banana" in the database, the popup that occurs when you click on the image of the ape contains the word "banana".

I want to achieve this with Fancybox2. Everything works fine, but the text in the popup only shows the first entry of the database. I've four images in my database and they are all on the screen, but no matter on which image you click, the text in the popup is the text of the first database entry.

I've done my research on the internet and found multiple solutions, like "use classes instead of id's in the jquery file", but none of them are working.

Here's my code:

HTML

<a class="fancybox" href="#data">
    <img src="<?php echo $row['image'];?>"/>
</a>


<div id="data">
    <p><?php echo $row['name'];?></p>
</div>

jQuery

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

I know that I use an ID to refer to the content, but I don't know how to make it a class. I hope someone can help me out.

If this is an duplicate question, my apologies. I'm new here and I didn't find any other solutions that could help me

Thanks in advance!

I haven't used fancybox in a while, but I am pretty sure that all you need to do, is set the title attribute:

<a class="fancybox" href="#data" title="<?php echo $row['name'];?>">
    <img src="<?php echo $row['image'];?>"/>
</a>

Agree with @Jeroen: you may not need the #data division, neither displaying the content as inline but as html (directly from the link) so try adding a (HTML5) data-* attribute to your <a> tags like :

<a class="fancybox" href="#" data-content="<?php echo $row['name'];?>">
    <img src="<?php echo $row['image'];?>" alt=""/>
</a>

Then, get the content from the data attribute and set type to html , using the beforeLoad callback like :

jQuery(document).ready(function ($) {
    $(".fancybox").fancybox({
        type: "html",
        beforeLoad: function () {
            this.content = $(this.element).data("content");
        }
    });
});

See JSFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM