将jQuery监听器附加到所有<a> elements and grab their ids?</a>

时间:2011-12-13 04:04:51

标签: jquery event-listener

我需要获取所有<a>链接的ID,以便根据它们的内容制作Ajax帖子

$(document).ready(function(e) {
   $('a').click(function(e) {
       var linker = this.attr('id');
       alert(linker);
       // Here I will then make an Ajax call, but I know how to do that :)
   });
});

4 个答案:

答案 0 :(得分:4)

this不是jQuery对象,因此您无法在其上调用attr;您需要$(this)才能使该方法可用。

$(document).ready(function(e) {
   $('a').click(function(e) {
       var linker = $(this).attr('id');
       alert(linker);
       // Here I will then make an Ajax call, but I know how to do that :)
   });
});

或者,您可以这样做:

var linker = this.id;

但这还不够jQuery ;)

答案 1 :(得分:1)

我将抵制纠正所有拼写和语法的冲动,并且恰到好处:

您的脚本应如下所示:

$(function(){
   $('a').click(function(){
      alert(this.id);
   };
});

您无需查看本地属性的“attr”属性。

答案 2 :(得分:0)

$(document).ready(function() {
   $('a').click(function(e) {
       var linker = $(this).attr('id');
       alert(linker);
       // Here I will then make an Ajax call, but I know how to do that :)
   });
});

答案 3 :(得分:0)

比使用jQuery获取ID更好的方法是使用this.id直接javascript:

$(document).ready(function(e) {
   $('a').click(function(e) {
       var linker = this.id;
       alert(linker);
       // Here I will then make an Ajax call, but I know how to do that :)
   });
});
只有当它比直接的javascript更好时,才应该使用jQuery。在这种情况下,jQuery方式$(this).attr(“id”)是两个不必要的函数调用,当this.id得到你想要的时候。

相关问题