1

for example i have:

<?php foreach($query as $q): ?>
        <div class="item">
        <?php echo img($q->images); ?>
        </div>
<?php endforeach; ?>

so this code renders 5 divs in a line, each line 5 divs, and this code:

<?php foreach($url->result() as $u): ?>

<script>
$(document).ready(function(){
    $('div.item').click(function(){

        setTimeout(function(){

                    window.open('<?php echo $u->url; ?>');


        }, 500)

    })
})
</script>
<?php break; ?>
<?php endforeach; ?>

doesn't matter what div we click, it will open a new window with the same url, but what if I have 5 different urls in my database, and I want that when we click the first div of each line it open one window with the first url and when we click the second it will open the second url

i thinked that this is possible by using classes, for example class="item1", item2, item3, item4, item5, but what if we have only 3 urls, not 5, in this case how can i make that the first three divs will open the first 3 urls, but the 2 left, will open the last, it is the 3 div

sorry for my poor english, maybe you have an idea of how to do this, thanks!

ps: i am using codeigniter

BlareStriker
  • 235
  • 1
  • 4
  • 14
  • Classic problem. Look [here](http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop/) – Jashwant Jun 13 '12 at 12:35
  • Just out interest, what is inside your `div`'s? What you could do, if you are only inserting images, is to simply use Anchor tags. – Gavin Jun 13 '12 at 13:04

2 Answers2

3

Instead of a class you can have id like item_1, item_2 etc. for each of the division and in javascript you can setup listeners in each of the divs separately.

<?php $index = 0;?>
<?php foreach($query as $q): ?>
        <div id="item_<?php echo $index++;?>">
        <?php echo img($q->images); ?>
        </div>
<?php endforeach; ?>

For Javascript the code goes as:

<?php $index = 0;?>
<?php foreach($url->result() as $u): ?>

<script>
$(document).ready(function(){
    $('#item_<?php echo $index++;?>').click(function(){

        setTimeout(function(){

                window.open('<?php echo $u->url; ?>');


    }, 500)

})
})
</script>
<?php break; ?>
<?php endforeach; ?>
sushil
  • 2,641
  • 3
  • 18
  • 24
1

2 options i can think of. first is to add the url as a data attribute of the div so data-url="url here" then you can just use $(this).attr('data-url') to get the link in the javascript action (may even be able to use data() but not sure on IE compatibility).

Second option would be to have a hidden anchor in the div, then in the javascript action you can just select the anchor within the clicked div to get the URL

Lee
  • 10,496
  • 4
  • 37
  • 45