dongying7667 2014-09-04 14:44
浏览 103
已采纳

在循环遍历类时引用$(this)

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

  • 写回答

2条回答 默认 最新

  • dpd3982 2014-09-04 15:19
    关注

    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));
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题