代码之家  ›  专栏  ›  技术社区  ›  Tony

jquery检索元素ID时出现问题

  •  0
  • Tony  · 技术社区  · 15 年前

    在下面的代码中,我需要获取引发事件的元素的ID

    $(document).ready(function () 
    {
        $(".selectors").live('change', function () 
        {
            $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
            {
                var idd = $(this).attr('id'); //here
            });
        });
    });
    

    但是 idd 总是“未定义”。为什么?

    2 回复  |  直到 15 年前
        1
  •  3
  •   lonesomeday    15 年前

    $.post 回调,值 this 将设置为不同于 live 打电话。您需要缓存 :

    $(document).ready(function () 
    {
        $(".selectors").live('change', function () 
        {
            var idd = this.id;
    
            $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
            {
                // idd is now the id of the changed element
            });
        });
    });
    
        2
  •  1
  •   Bryan A    15 年前

    这个 $(this) 在你的内心 .post 函数实际上不是要在父循环中迭代的集合中的当前元素。修复:

    $(".selectors").live('change', function () 
    {
        $thisElement = $(this);
    
        $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
        {
            var idd = $thisElement.attr('id'); //here
        });
    });