如何获取点击元素的ID

时间:2015-02-25 05:09:48

标签: javascript jquery ajax jsp servlets

我想检索点击元素的ID(在' onclick;事件。

<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>     

这是调用此函数的元素。我想从上面的脚本中获取这个raw的ID。这仅适用于我直接提供&#34; clickableRow&#34;至于脚本的id。 &#34; ID&#34;是动态改变

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

3 个答案:

答案 0 :(得分:1)

无需内联事件处理程序

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

然后

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
        });
    });
})

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

只需使用此

即可
onclick="myFunction(this.id)

而不是

onclick="myFunction(this)

获取我的功能

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