How to get the attributes of a HTML element using JQuery?

前端 未结 4 908
囚心锁ツ
囚心锁ツ 2020-12-12 07:02

I am wondering whether there is a way in which I can get the value within a given HTML element using JQuery?

Example

&l         


        
相关标签:
4条回答
  • 2020-12-12 07:24

    If you only want to get the ID of the <span/> you clicked then it's better to apply a click event handler to each span and catch the attribute value.

    $("span").click(function() {
      return $(this).attr("id");
    });
    
    0 讨论(0)
  • 2020-12-12 07:28

    can't help but noticed,

    you need something like this..

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

    good to play demo

    0 讨论(0)
  • 2020-12-12 07:33

    You kind of need a different selector in order to tell jQuery which span element to look at.

    $("span").attr("id")
    

    Which would get the Id attr value of all spans on the page.

    For example, if you had

    <span id="mySpan" class="mySpanClass"></span>
    

    you could get the IDs of all the spans with class "mySpanClass" using:

    $("span[class='mySpanClass']").attr("id")
    

    Documentation here: http://api.jquery.com/attr/

    0 讨论(0)
  • 2020-12-12 07:40

    Get: $("#45463_test").attr('id'); Set: $("#45463_test").attr('id','new value');

    http://api.jquery.com/attr/

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