jquery: how to get the value of id attribute?

后端 未结 4 529
走了就别回头了
走了就别回头了 2020-12-02 18:10

Basic jquery question. I have an option element as below.

  

相关标签:
4条回答
  • 2020-12-02 18:39

    You need to do:

    alert($(this).attr('value'));
    
    0 讨论(0)
  • 2020-12-02 18:44

    To match the title of this question, the value of the id attribute is:

    var myId = $(this).attr('id');
    alert( myId );
    

    BUT, of course, the element must already have the id element defined, as:

    <option id="opt7" class='select_continent' value='7'>Antarctica</option>
    

    In the OP post, this was not the case.


    IMPORTANT:

    Note that plain js is faster (in this case):

    var myId = this.id
    alert(  myId  );
    

    That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.

    0 讨论(0)
  • 2020-12-02 18:45

    You can also try this way

    <option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
    

    jquery

    $('.select_continent').click(function () {
    alert($(this).data('value'));
    });
    

    Good luck !!!!

    0 讨论(0)
  • 2020-12-02 19:03
    $('.select_continent').click(function () {
        alert($(this).attr('value'));
    });
    
    0 讨论(0)
提交回复
热议问题