谁还没个明天 2010-07-13 17:11 采纳率: 50%
浏览 887
已采纳

如何使用 jQuery 获取元素的 ID?

<div id="test"></div>
<script>
  $(document).ready(function() {
    alert($('#test').id);
  });  
</script>

Why doesn't the above work, and how should I do this?

转载于:https://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery

  • 写回答

14条回答 默认 最新

  • YaoRaoLov 2010-07-13 17:12
    关注

    The jQuery way:

    $('#test').attr('id')
    

    In your example:

    <div id="test"></div>
    
    $(document).ready(function() {
        alert($('#test').attr('id'));
    }); 
    

    Or through the DOM:

    $('#test').get(0).id;
    

    or even :

    $('#test')[0].id;
    

    and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

    an alternative for DOM selector in jquery is

    $('#test').prop('id')
    

    which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 R语言 拟时序分析降维图如何减少分支
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统