0

This script loops through a number 1-20. I discovered that the tags are repeated 20 times.

<?php for ($i = 1; $i <= 20; $i++) { ?>
    <button id="btn-<?php echo $i;?>">Button<?php echo $i;?></button>
    <script type="text/javascript">
        $('#btn-<?php echo $i;?>').clck(function() {
            alert("you clicked button <?php echo $i;?>");
        }); 
<?php } ?>

I want to do the $('#btn-<?php echo $i;?>').clck(function() {.... once outside the loop

0

1 Answer 1

3

The code you've written here is an anti-pattern. Use a common class on all the elements in the loop and attach a single event handler to that class. For example:

<?php for ($i = 1; $i <= 20; $i++) { ?>
    <button class="foo" data-id="btn-<?php echo $i;?>">Button<?php echo $i;?></button>
<?php } ?>
// in an external .js file far, far away
$('.foo').click(function() {
    console.log("You clicked button " + $(this).data('id'));
});

Here's a runnable code snippet. Note PHP only has to generate the HTML below. The JavaScript will then attach the click event handler to each button.

$('.foo').click(function() {
  console.log("You clicked button " + $(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="foo" data-id="1">Button 1</button>
<button class="foo" data-id="2">Button 2</button>
<button class="foo" data-id="3">Button 3</button>
<button class="foo" data-id="4">Button 4</button>

Sign up to request clarification or add additional context in comments.

1 Comment

I was in the middle of answering something similar but didn't want to effectively duplicate your answer. I included a runnable code snippet to give the OP a tangible result. Feel free to edit/remove it if you find it confusing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.