简体   繁体   中英

How to get the php dynamic id from the jquery click function

Not getting alert on the anchor click why this happening .

<td id="hovercolor">
    <a class="tt" style="text-decoration:
none;color: black;" href="javascript:void(0);" id="<?php echo
$data->id; ?>"></a>
    <?php echo $data->title; ?>
</td>

Script I am using to get the alert is :

<script type="text/javascript">
    $('#new1').click(function() {
        alert('ok');
    });
</script>

First wrap you code in a document ready statement,second you may want to use a class if you have multiple items

<script type="text/javascript">
    $(function(){
          $('.tt').click(function() {
              alert('ok');
          });
     })

   </script>

Assuming that your ID is correct, you may use .on() to select those elements that are dynamically created. And since the ID are dynamic, you need to created a unique class for the links and use it instead

$('table').on('click', '.unique_link_class', function() {
    alert('ok');
});

You should change two things in your code snippet:

1) I believe $data->id will print an integer values, so I would suggest to use class instead, which is class="tt"

2) second change will be, you should put this function inside document.ready jquery function. So the updated jquery code should be,

$(document).ready(function(){
    $('.tt').on('click',function(){    //  Notice that I have used `on` here
        alert();
    });
});

use class name instead of id . Your id may be integer.

 <script type="text/javascript">
            $('.tt').click(function() {
                alert('ok');
            });
 </script>

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