2010-07-29 45 views
0

我是jquery的新手,想知道是否有人可以帮助我,我相信这是一个简单的解决方案。为什么我不能得到一个元素的ID - jquery

我试图让当点击一个链接的ID,然后提醒标识出这样的:

缺少什么我在这里?导致萤火虫给我一个'id is not defined'的错误。

$(document).ready(function(){ 

    $("a.category").click(function(){ 
     $.post("index.php", { id: "$(this).attr('id')"}, 
     function(data){ 
     alert("Data Loaded: " + id); 
     }); 
    //return false to insure the page doesn't refresh 
    return false; 
    }); 

}); 

感谢有这方面的帮助。

回答

2

通过编写{ id: "$(this).attr('id')" },您正在创建一个对象,其id属性设置为文字字符串"$(this).attr('id')"

要发布点击元素的实际ID,您需要删除引号并将id属性设置为表达式的值,如下所示:{ id: $(this).attr('id') }

此外,表达式{ id: $(this).attr('id') }创建一个具有id属性的对象。
它不会创建任何id变量,因此您不能在回调中使用非变量id

要解决这个问题,你需要做一个变量,就像这样:

$(document).ready(function() {  
    $("a.category").click(function(){ 
     var id = $(this).attr('id'); 

     $.post("index.php", { id: id }, 
      function(data){ 
       alert("Data Loaded: " + id); 
      } 
     ); 
     //return false to insure the page doesn't refresh 
     return false; 
    });  
}); 
+0

嘿Slaks,错字在第一行:你的意思是'id'财产。 – 2010-07-29 04:40:23

相关问题