0

I'm using the data attribute to pass data with links but it happens very often that this kind of declaration becomes redundant e.g I have an array for images that I iterate through and display on the screen. Each of them have an image id and a set of options presented as links. Im passing the image_id in a data attribute right now in each link. But there has to be a way to only declare the image_id once and then collect this data when clicking one of the links associated with the image.

    for($i = 0; $i <= ($image_array_length - 1); $i++){ ?>

<img src="somesrc" />

<a href="#" data-image_id="<?php echo $image['image_id']; ?>">Image option 1</a>
<a href="#" data-image_id="<?php echo $image['image_id']; ?>">Image option 2</a>
<a href="#" data-image_id="<?php echo $image['image_id']; ?>">Image option 3</a>

<?php }?>

so instead of having to declare the image id for each link I would like to have something like this:

    for($i = 0; $i <= ($image_array_length - 1); $i++){ ?>

<img src="somesrc" id="data-placeholder" data-image_id="<?php echo $image['image_id']; ?>" />

<a href="#" class="js-selector">Image option 1</a>
<a href="#" class="js-selector">Image option 2</a>
<a href="#" class="js-selector">Image option 3</a>

<?php }?>

But the problem I'm facing is that there are several images and each of them will have the same id on the img element that means that I cant identify the specific image_id. So in javascript:

$(".js-selector").click(function(){
    var image_id = $("#placeholder").data("image_id");
    some statements...
});

How should javascript know which image_id to collect if i want to declare the image_id as in the second HTML example?

4

0 回答 0