最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get in 'clicked' element in jquery ajax success callback - Stack Overflow

programmeradmin8浏览0评论

This is one easy (I hope) question which is bugging me for years. How do you get element that fired event which triggered the ajax request? Here is an example:

<button id="clickme">Click me</button>
$("#clickme").click(function(e){
    var i_need_this=e.target;
    alert(i_need_this); //nice!
    $.ajax({
            url:'/',

            type: 'GET',
            success: function( data, status, jqXHR  ) {
                alert('success');
              //console.log( ??? ); Get i_need_this from somewhere?       
            }
        });

})

Live: /

Thanks in advance!

This is one easy (I hope) question which is bugging me for years. How do you get element that fired event which triggered the ajax request? Here is an example:

<button id="clickme">Click me</button>
$("#clickme").click(function(e){
    var i_need_this=e.target;
    alert(i_need_this); //nice!
    $.ajax({
            url:'http://echo.jsontest./',

            type: 'GET',
            success: function( data, status, jqXHR  ) {
                alert('success');
              //console.log( ??? ); Get i_need_this from somewhere?       
            }
        });

})

Live: http://jsfiddle/8F3u2/

Thanks in advance!

Share Improve this question asked Aug 4, 2014 at 12:52 AmantelAmantel 7391 gold badge9 silver badges21 bronze badges 3
  • 2 Did you try this? console.log( i_need_this); – Anton Commented Aug 4, 2014 at 12:54
  • @Praveen I think there is no such variable as e inside success callback; UPD Wow, it seems I was wrong and you where right! Sorry. Still messing with scope in js. – Amantel Commented Aug 4, 2014 at 13:24
  • @Anton I tried this. Well, what can I say - both yours and Praveen's methods works. Thanks! – Amantel Commented Aug 4, 2014 at 13:26
Add a ment  | 

1 Answer 1

Reset to default 11

You can use context param here:

$.ajax({
        url:'http://echo.jsontest./',
        context:this, // <------this is the cliked button
        type: 'GET',
发布评论

评论列表(0)

  1. 暂无评论