【问题标题】:Ajax jQuery , beginner questionAjax jQuery , 初学者问题
【发布时间】:2008-12-28 03:25:49
【问题描述】:

我正在尝试进行 ajax 调用以获取会话数据,以便在页面像这样加载后插入到我的页面中

jQuery(function(){ // Add Answer

  jQuery(".add_answer").livequery('click',function(){
    var count = $(this).attr("alt");
    count++;
    var count1 = count-1;

    $.get('quiz/select', function(p_type){  // Ajax Call for Select Data

      $(this).parents('div:first').find('.a_type_'+count1+'').after('' + p_type + '');
      $(this).attr("alt", count);

    });
  });
});

找到了我正在调用的文件,但它的内容没有被 'p_type' 打印出来 并且函数的$(this).attr("alt", count); 部分没有执行

注意:我的框架使用 CodeIgniter,js 使用 jquery

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    我相信您的问题与 $(this) 的范围有关。因为你的 ajax get 函数嵌套在你的 livequery 函数中,在另一个匿名函数中,我敢打赌 $(this) 现在指的是你的 $.get() 调用或其他东西。

    您需要尽快缓存 $(this) 在您知道它选择了正确的对象的位置:

    jQuery(".add_answer").livequery('click',function()
    {
        var add_answer = $(this);
    
        $.get(...)
        {
            add_answer.parents('div:first')...
        }
    }
    

    上面的代码应该缓存add_answer元素,但是我的livequery知识有点生疏。

    关于您的代码的一些建议:

    • 与 jQuery() 或 $() 快捷方式的使用保持一致,它们的作用相同。
    • 围绕整个 sn-p 的匿名函数是怎么回事?这只是一个简化的例子吗?它可能应该被替换为 $(document).ready(function { ... });

    【讨论】:

    • 使用 $(function() { ... }) 等价于 $(document).ready(function { ... });
    • 你是对的。我一直发现 $(document).ready() 的意图更清晰。
    【解决方案2】:

    “this”是 Javascript 中的一个特殊关键字。 在您的外部函数中,它指的是 .add_answer 元素。 在您的内部函数中,它指的是窗口。

    jQuery(".add_answer").livequery('click',function(){
      var self = this;
      // ...
      $.get('quiz/select', function(p_type){
        // ...
        $(self).attr("alt", count);
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 2011-03-09
      • 1970-01-01
      • 2020-01-04
      • 2020-11-23
      • 2015-03-16
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多