简体   繁体   中英

How can I get the value of an ID into Ajax using $(this)?

Here I have 4 buttons. How can I get the value of the id for each button onto the end of data: "id=" within the ajax part? Bare in mind, each id is unique as its using a numeric counter.

So for examples sake, if I clicked the third button then the id would equal 3 , if I clicked the second button, the id would 2... and so on. Using $("a").attr('id') kind of works but it will grab the first <a> tag and stick with that value for which ever button you press. I also tried $(this).attr('id') but that doesn't work either.

Any suggestions?

 <?php 
    $counter = 0;

        echo '
      <button><a class="test" id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
    ';

    ?>
      <script id="source" language="javascript" type="text/javascript">

      $("button").click(function () 
      {

        //-------------------------------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-------------------------------------------------------------------------------------------
        $.ajax({                                      
          url: 'api.php',                  //the script to call to get data          
          data: "id="+ $("a").attr('id'),                        //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
          dataType: 'json',                //data format      
          success: function(data)          //on recieve of reply
          {
            var id = data[0];              //get id
            var vname = data[1];           //get name
            //--------------------------------------------------------------------------------------
            // 3) Update html content
            //--------------------------------------------------------------------------------------
            $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
          }
        }); 
      }); 
      </script>

As suggested in the comments, this should work.

$(this).find('a').attr('id')

If you didn't want to traverse the DOM, however, you could just store the value in the button.

<button counterid="'.++$counter.'"><a class="test">Test</a></button>
<button counterid="'.++$counter.'"><a>Test</a></button>
<button counterid="'.++$counter.'"><a>Test</a></button>
<button counterid="'.++$counter.'"><a >Test</a></button>

Use the above for your HTML and then your JS would be:

$(this).attr('counterid')

I don't know php but the idea is the same.

$("button").click(function () {
  //-------------------------------------------------------------------------------------------
  // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
  //-------------------------------------------------------------------------------------------
   var id = $(this).find('a').attr('id');
   $.ajax({                                      
     url: 'api.php',                  //the script to call to get data          
     data: "id="+id,                        //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
     dataType: 'json',                //data format      
     success: function(data) {
       var id = data[0];              //get id
       var vname = data[1];           //get name
       //--------------------------------------------------------------------------------------
      // 3) Update html content
      //--------------------------------------------------------------------------------------
      $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
    }
  }); 
}); 

$("a").attr('id') will retrieve all the anchor tags on the page and give you the first one's id.

In the context of your event handler function, this refers to the button element which was clicked.

To get the anchor tag inside the clicked button, you can use jQuery's .find method:

$(this).find('a').attr('id');

This will find any child anchor tags and return the id attribute of the first one.

 $("button").click(function (e) {

   var id = $(e.target).attr('id');

    $.ajax{ 
        //...make the ajax call as needed
    });
});

e is the event, e.target is the button element that triggered the click, you can then get its ID directly.

example http://jsfiddle.net/ZRA9K/

See http://api.jquery.com/click/

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