jQuery:从类选择器获取ID

60

有没有办法从类似以下内容中获取元素的id:

<a href="#" class="test" id="test_1">Some text</a>
<a href="#" class="test" id="test_2">Some text</a>
<a href="#" class="test" id="test_3">Some text</a>

然后我绑定

$('.test')

所以当我点击其中一个元素时,会返回该元素的id吗?

7个回答

112

哎呀..如果我理解正确,那么它应该是如此简单:

$('.test').click(function() {
  console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="test" id="test_1">Some text</a>
<a href="#" class="test" id="test_2">Some text</a>
<a href="#" class="test" id="test_3">Some text</a>

你可以在事件处理程序内部通过访问底层的 DOM 节点,仅使用 id 属性 来进行 访问

47

使用 jQuery 中的 "attr" 方法。

$('.test').click(function(){
    var id = $(this).attr('id');
});

1
基本问题是:一旦你得到了this,假设OP试图通过ID找到元素而不是通过元素找到ID,那么你实际上不需要id - Kobi
1
没错。不过他可能想要显示id的名称。 - benck
我同意两者都可以,这完全取决于你的具体任务! :) - Oliver M Grech
selected.id 对我来说会返回未定义,但 selected.attr('id') 可以正常工作。 - dave

8
当您添加单击事件时,this 返回已单击的元素。因此,您可以只使用 this.id
$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/


8
自jQuery 1.6版本以来,您可以(有些人会说应该)使用.prop而不是.attr
$('.test').click(function(){
    alert($(this).prop('id'));
});

这个问题在这篇文章中有更详细的讨论: .prop()和.attr()的区别


4

如果您使用了箭头函数,请注意,因为this.id的值将为undefined。今天我浪费了10分钟时间,纳闷发生了什么。


什么是箭头函数? - Oliver M Grech
1
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Functions#Arrow_functions - nasoj1100

3
$(".class").click(function(){
    alert($(this).attr('id'));
});

只有在jquery按钮点击时,我们才能做到这一点,该类应该在那里编写。

0

这些示例对我都没有用。

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接