0

I have an <a> tag coming back from a php file in a json format, it is as follows:

$subarray[] = '<a href="#" onclick="profile(\'' . $row['id'] . '\')" class="buttons">...</a>';

This one works fine. However, reading some material on unobtrusive JavaScript, I'd like to remove that onclick="profile(\'' . $row['id'] . '\')" and instead add an id to the tag, and then listen for the time the id is clicked. Hence, the code will be something like the following:

$subarray[] = '<a href="#" class="buttons" id="some">...</a>';

However, when I try to listen for the event to happen, in a code like the following:

$("#some").click(function() {
        alert('hi');
    });

nothing happens. I would much appreciate it if you could tell me how to solve the problem, and let me know what is the best practice here.

H. M..
  • 568
  • 6
  • 15

1 Answers1

0

You have got all of this right so far only difference is that you need to echo the link containing in the array to get displayed on the webpage and by which we can click it

Check out this

<?php
$subarray[] = '<a href="#" class="buttons" id="some">...</a>';
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <?php echo $subarray[0];?>
<script>
    $("#some").click(function() {
        alert('hi');
    });
</script>
</body>
</html>
Kunal Raut
  • 2,495
  • 2
  • 9
  • 25