jQuery获取< li>的ID/值点击功能后的元素 [英] jQuery get the id/value of <li> element after click function

查看:102
本文介绍了jQuery获取< li>的ID/值点击功能后的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何提醒点击的<li>项目的ID?

How can I alert the id of the <li> item clicked?

<ul id='myid'>
  <li id='1'>First</li>
  <li id='2'>Second</li>
  <li id='3'>Third</li>
  <li id='4'>Fourth</li>
  <li id='5'>Fifth</li>
</ul>

(任何可以替换id的东西可能都是值,或者其他也可以使用的东西.)

(Anything that can replace the id may be value or something else will also work.)

推荐答案

$("#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
});

如果您要使用以下内容替换ID:

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/

这篇关于jQuery获取&lt; li&gt;的ID/值点击功能后的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆