Javascript jquery:从类选择器中获取 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5470729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:19:36  来源:igfitidea点击:

jquery: get id from class selector

javascriptjqueryhtml

提问by Oliver M Grech

Is there any way that I can get the id of an element from something like:

有什么方法可以从以下内容中获取元素的 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>

and then I bind

然后我绑定

$('.test')

$('.test')

so when I click one of the elements I get back the id?

所以当我点击其中一个元素时,我会得到 id 吗?

回答by jAndy

Doh.. If I get you right, it should be as simple as:

Doh .. 如果我没听错的话,应该很简单:

$('.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>

You can just accessthe id propertyover the underlaying dom node, within the event handler.

您只需访问id属性在垫层DOM节点,事件处理程序中。

回答by benck

Use "attr" method in jquery.

在 jquery 中使用“attr”方法。

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

回答by Jonathon Bolster

When you add a click event, thisreturns the element that has been clicked. So you can just use this.id;

添加点击事件时,this返回被点击的元素。所以你可以使用this.id;

$(".test").click(function(){
   alert(this.id); 
});

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

示例:http: //jsfiddle.net/jonathon/rfbrp/

回答by Tony L.

As of jQuery 1.6, you could (and some would say should) use .propinstead of .attr

从 jQuery 1.6 开始,您可以(有些人会说应该)使用.prop而不是 . 属性

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

It is discussed further in this post: .prop() vs .attr()

在这篇文章中进一步讨论:.prop() vs .attr()

回答by nasoj1100

Be careful if you use fat arrow functions as you will get undefined for this.id Wasted 10 minutes today wondering what the hell was going on

使用粗箭头函数时要小心,因为你会得到 undefined for this.id 今天浪费了 10 分钟想知道到底发生了什么

回答by cr7 aj7

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

only on jquery button click we can do this class should be written there

只有在 jquery 按钮点击我们可以做这个类应该写在那里

回答by N.Yotsov

Nothing from this examples , works for me

这个例子中没有任何内容对我有用

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'));
    });