jquery: get id from class selector

前端 未结 7 1297
离开以前
离开以前 2020-12-23 09:22

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

Some text


        
相关标签:
7条回答
  • 2020-12-23 09:34

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

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

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

    0 讨论(0)
  • 2020-12-23 09:38

    Use "attr" method in jquery.

    $('.test').click(function(){
        var id = $(this).attr('id');
    });
    
    0 讨论(0)
  • 2020-12-23 09:38

    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'));
        });
    
    0 讨论(0)
  • 2020-12-23 09:40

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

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

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

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-23 09:49

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

    $('.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 access the id property over the underlaying dom node, within the event handler.

    0 讨论(0)
提交回复
热议问题