如何使用jQuery获取元素的ID? [英] How can I get the ID of an element using jQuery?

查看:59
本文介绍了如何使用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?

推荐答案

jQuery方式:

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

在您的示例中:

$(document).ready(function() {
  console.log($('#test').attr('id'));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

或通过DOM:

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

甚至:

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

以及在JQuery甚至$('#test')[0]中使用$('#test').get(0)的原因是$('#test')是JQuery选择器,并且返回结果的array()并不是其默认功能的单个元素

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

jquery中DOM选择器的替代方法是

an alternative for DOM selector in jquery is

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

.attr()$('#test').prop('foo')不同的

抓住了指定的DOM foo属性,而$('#test').attr('foo')抓住了指定的HTML foo属性,您可以找到有关差异的更多详细信息

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.

这篇关于如何使用jQuery获取元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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