简体   繁体   中英

How to get the clicked element's ID

I want to retrieve the ID of the clicked element (on the 'onclick; event.

<script>


 function myFunction(element)
 {
     var $id = element.id;
     $($id).click(function() {           
                    $.get('ajaxTestSrvlt?test=1', function(responseText) {                      
                          $('#firstName').val(responseText);      with the response text.
                    });
                });
 };

</script>     

This is the element this function was called upon. I would like to get the ID of this raw from the above script. This only works when I directly give the "clickableRow" as to id to the Script. The "ID" is to be changed dynamically

 <tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal" onclick="myFunction(this)"> 

There is no need to have a inline event handler

<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal">

then

jQuery(function () {
    $('.clickable-row').click(function () {
        var $this = $(this),
            id = this.id;

        $.get('ajaxTestSrvlt?test=1', function (responseText) {
            $('#firstName').val(responseText);
            //here `id` is the id of the clicked tr
        });
    });
})

Try this

function myFunction(ele)
{
    var id=$(ele).attr("id");
     $('#'+id).click(function() {           
        //code here
     }); 
}

Simply use this

onclick="myFunction(this.id)

Instead of

onclick="myFunction(this)

Get your id on my function

function myFunction(getid) {
   alert(getid);
}

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