jQuery get the id/value of
  • element after click function
  • 后端 未结 4 1028
    忘了有多久
    忘了有多久 2020-11-28 04:59

    How can I alert the id of the

  • item clicked?

    • First
    • Second
  • 4条回答
    •  我在风中等你
      2020-11-28 05:35

      $("#myid li").click(function() {
          alert(this.id); // id of clicked li by directly accessing DOMElement property
          alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
          alert($(this).html()); // gets innerHTML of clicked li
          alert($(this).text()); // gets text contents of clicked li
      });
      

      If you are talking about replacing the ID with something:

      $("#myid li").click(function() {
          this.id = 'newId';
      
          // longer method using .attr()
          $(this).attr('id', 'newId');
      });
      

      Demo here. And to be fair, you should have first tried reading the documentation:

      • http://api.jquery.com/category/selectors/
      • http://api.jquery.com/category/events/
      • http://api.jquery.com/attr/

    提交回复
    热议问题