glaux
glaux

Reputation: 710

Referencing $(this) while looping through a class

I have a number of tables on a page. The contents are generated by a php script given a keyword (kuid - loaded from a database) and loaded in with jQuery.

On the page they look something like this:

<table class="className" kuid="someInteger"></table>

Here is the jQuery I came up with:

jQuery('.className').each(function(){
  var kuid = jQuery(this).attr('kuid');
  jQuery.post('data.php',{kuid: kuid},function(data){
    jQuery(this).html(data);
  });
});

and the data.php:

$kuid = $_POST['kuid'];
echo 'Content for this ID: '.$kuid.'!';

However it throws an 'Uncaught TypeError'. Apperently I'm not allowed to use the $(this) keyword, but I don't understand why.

This code works somewhat:

var kuid = jQuery('.className').attr("kuid");
jQuery.post(data.php',{kuid: kuid},function(data){
  jQuery('.className').html(data);
});

but it gives every table the same contents based on the first occurence of "kuid".

Upvotes: 0

Views: 76

Answers (2)

hsz
hsz

Reputation: 152216

Just assign $(this) to a variable before going inside post:

jQuery('.className').each(function(){
  var kuid = jQuery(this).attr('kuid'),
      that = jQuery(this);

  jQuery.post('data.php',{kuid: kuid},function(data){
    that.html(data);
  });
});

Upvotes: 0

feesar
feesar

Reputation: 500

u can use jquery function $.proxy

jQuery('.className').each(function(){
  var kuid = jQuery(this).attr('kuid');
  jQuery.post('data.php',{kuid: kuid},$.proxy(function(data){
    jQuery(this).html(data);
  }, this));
});

Upvotes: 1

Related Questions