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

为什么上述方法不起作用,我应该怎么做?


#1楼

$('tagname').attr('id');

使用上面的代码,您可以获得ID。


#2楼

以上答案很好,但是随着jquery的发展..您也可以这样做:

var myId = $("#test").prop("id");

#3楼

$.fn.extend({id : function() {return this.attr('id');}
});alert( $('#element').id() );

当然需要一些检查代码,但是很容易实现!


#4楼

如果要获取某个元素的ID,则由类选择器说,当在该特定元素上触发一个事件(在本例中为click事件)时,将执行以下操作:

 $('.your-selector').click(function(){var id = $(this).attr('id');});

#5楼

重要提示:如果要使用jQuery创建新对象并绑定事件,则必须使用prop而不是attr ,如下所示:

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");


#6楼

这可以是元素id,class,也可以自动使用甚至

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================

#7楼

这最终将解决您的问题:

假设您在页面上有许多按钮,并且您想根据其ID使用jQuery Ajax(或不使用ajax)更改其中一个按钮。

还可以说您有许多不同类型的按钮(用于表单,用于批准和用于类似目的),并且您希望jQuery只处理“喜欢”按钮。

这是一个有效的代码:jQuery将仅处理.cls-hlpb类的按钮,它将获取被单击的按钮的ID,并将根据来自Ajax的数据对其进行更改。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",{name: "Donald Duck",city: "Duckburg"},function(data,status){//parsing the data should come here://var obj = jQuery.parseJSON(data);//$("#"+id).val(obj.name);//etc.if (id=="btnhlp-1")$("#"+id).attr("style","color:red");$("#"+id).val(data);});
});});
</script>
</head>
<body><input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn">    </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn">    </input></body>
</html>

代码取自w3schools,并已更改。


#8楼

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()结果的功能不是单个元素

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

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

这与.attr()$('#test').prop('foo') ,它获取指定的DOM foo属性,而$('#test').attr('foo')获取指定的HTML foo属性,您可以在此处找到有关差异的更多详细信息。


#9楼

$('selector').attr('id')将返回第一个匹配元素的ID。 参考 。

如果匹配的集合包含多个元素,则可以使用常规的.each 迭代器返回包含每个id的数组:

var retval = []
$('selector').each(function(){retval.push($(this).attr('id'))
})
return retval

或者,如果您愿意加一点勇气,可以避免使用包装器,而可以使用.map 快捷方式 。

return $('.selector').map(function(index,dom){return dom.id})

#10楼

$('#test')返回一个jQuery对象,因此不能简单地使用object.id来获取其Id

您需要使用$('#test').attr('id') ,它返回所需的元素ID

也可以按照以下步骤进行操作:

$('#test').get(0).id等于document.getElementById('test').id


#11楼

id是html Element的属性。 但是,当您编写$("#something") ,它将返回一个jQuery对象,该对象包装了匹配的DOM元素。 要获取第一个匹配的DOM元素,请调用get(0)

$("#test").get(0)

在此本机元素上,您可以调用id或任何其他本机DOM属性或函数。

$("#test").get(0).id

这就是为什么id在您的代码中不起作用的原因。

或者,使用jQuery的attr方法作为其他答案,以获取第一个匹配元素的id属性。

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

#12楼

.id不是有效的jquery函数。 您需要使用.attr()函数来访问元素拥有的属性。 您可以使用.attr()通过指定两个参数来更改属性值,或者通过指定一个来获取值。

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


#13楼

这是一个古老的问题, 但是从2015年开始可能会有效:

$('#test').id;

您还可以进行分配:

$('#test').id = "abc";

只要定义以下JQuery插件:

Object.defineProperty($.fn, 'id', {get: function () { return this.attr("id"); },set: function (newValue) { this.attr("id", newValue); }
});

有趣的是,如果element是DOM元素,则:

element.id === $(element).id; // Is true!

#14楼

可能对其他发现此线程的人有用。 以下代码仅在您已经使用jQuery的情况下有效。 该函数始终返回一个标识符。 如果该元素没有标识符,则函数会生成该标识符并将其附加到该元素。

var generatedIdCounter = 0;$.fn.id = function() {var identifier = this.attr('id');if(!identifier) {generatedIdCounter++;identifier = 'isGenerated_' + generatedIdCounter;this.attr('id', identifier);}return identifier;
}

如何使用:

$('.classname').id();$('#elementId').id();

#15楼

好吧,似乎还没有解决方案,并且想提出我自己的解决方案,它是JQuery原型的扩展。 我将其放在JQuery库之后加载的Helper文件中,因此检查window.jQuery

if (window.jQuery) {$.prototype.id = function () {if (this.length > 1) {var val = [];this.each(function (idx, el) {val.push($(el).id());});return val;} else {return this.attr('id');}}
}

它可能并不完美,但是它可能成为包含在JQuery库中的开始。

返回单个字符串值或字符串值数组。 字符串值数组是用于使用多元素选择器的事件。


#16楼

$('#test').attr('id')在您的示例中:

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

#17楼

由于id是属性,因此可以使用attr方法获取它。


#18楼

<html>
<head><link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></head>
<?php// include Database connection file include("db_connection.php");// Design initial table header $data = '<table class="table table-bordered table-striped"><tr><th>No.</th><th>First Name</th><th>Last Name</th><th>Email Address</th><th>Update</th><th>Delete</th></tr>';$query = "SELECT * FROM users";if (!$result = mysqli_query($con, $query)) {exit(mysqli_error($con));}// if query results contains rows then featch those rows if(mysqli_num_rows($result) > 0){$number = 1;while($row = mysqli_fetch_assoc($result)){$data .= '<tr><td>'.$number.'</td><td>'.$row['first_name'].'</td><td>'.$row['last_name'].'</td><td>'.$row['email'].'</td><td><button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button></td></tr>';$number++;}}else{// records now found $data .= '<tr><td colspan="6">Records not found!</td></tr>';}$data .= '</table>';echo $data;
?><script type="text/javascript">function DeleteUser(id) {var conf = confirm("Are you sure, do you really want to delete User?");if (conf == true) {$.ajax({url:'deleteUser.php',method:'POST',data:{id:id},success:function(data){alert('delete successfully');}}
});deleteUser.php<?php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{// include Database connection fileinclude("db_connection.php");// get user id$user_id = $_POST['id'];// delete User$query = "DELETE FROM users WHERE id = '$user_id'";if (!$result = mysqli_query($con, $query)) {exit(mysqli_error($con));}
}
?>

#19楼

它不能回答OP,但可能对其他人很有趣:在这种情况下,您可以访问.id字段:

$('#drop-insert').map((i, o) => o.id)

如何使用jQuery获取元素的ID?相关推荐

  1. jquery获取元素在文档中的位置信息以及滚动条位置(转)

    jquery获取元素在文档中的位置信息以及滚动条位置 http://blog.csdn.net/qq_34095777/article/details/78750886     原文链接 原创 201 ...

  2. jquery获取元素索引值index()

    jquery获取元素索引值index() 作者: 梅川内酷 于 13-04-26 热度:384 jquery获取元素索引值index()方法: jquery的index()方法 搜索匹配的元素,并返回 ...

  3. jquery获取元素四种方式。

    jquery获取元素四种方式. 当你成功引入jquery插件之后,就可以用jquery的语法来获取html元素. js获取只有document.getElementById或者通过名称来获取. 而jq ...

  4. js jquery 获取元素(父节点,子节点,兄弟节点)

    js jquery 获取元素(父节点,子节点,兄弟节点) js 获取元素(父节点,子节点,兄弟节点) var test = document.getElementById("test&quo ...

  5. jquery获取元素宽高

    前言 jquery获取元素宽高 <!DOCTYPE html> <html lang="zh" > <head><meta charset ...

  6. jquery获取元素的索引_如何在jQuery中获取具有特定索引的元素

    jquery获取元素的索引 In this post, we are going to discuss how to get an element with a specific index. jQu ...

  7. html获取边缘元素,JQuery 获取元素到浏览器可视窗口边缘的距离

    获取元素到浏览器可视窗口边缘的距离 by:授客 QQ:1033553122 1.测试环境 JQuery-3.2.1.min.js 下载地址: https://gitee.com/ishouke/fro ...

  8. js jquery 获取元素(父节点,子节点,兄弟节点),元素筛选

    js jquery 获取元素(父节点,子节点,兄弟节点) 一,js 获取元素(父节点,子节点,兄弟节点) var test = document.getElementById("test&q ...

  9. js获取元素的id值

    -------------获取元素的id值---------------- <div class="box">     <span>实例演示:获取被点击元素 ...

最新文章

  1. 进程句柄表初始化,扩展,插入删除句柄源码分析
  2. 使用SAP WebIDE进行一个典型的bug修复流程
  3. ubuntu修改用户名、计算机名、主目录名
  4. 计算机毕业设计之java+springboot基于vue的4S店车辆管理系统
  5. android TextView(文本框)详解
  6. 【毕业设计】QT从入门到实战:实现模仿QQ通讯,也是在校的最后一篇博文。
  7. 【机器学习笔记】【随机森林】【回归器】【填充缺失值】
  8. [EndNote]EndNote在Word中的工具条消失了怎么办?-知乎转载
  9. Golang神奇的2006-01-02 15:04:05
  10. 基于模板匹配和遗传算法的人眼定位
  11. 微信小程序计算两个日期之间相差几天
  12. activiti——结束事件
  13. 我远行,故我在——海陀行点滴感受
  14. MyBatis实现数据的增删查改
  15. 手机上的廉价快感,真的得戒掉
  16. 关于用python爬虫白嫖漫画这档子事
  17. MATLAB中AVP例子学习
  18. 8岁学编程已经晚了?6个网站让你在家教孩子学编程
  19. cad如何转换成jpg格式
  20. 【.Net Core底层入门】MSIL入门

热门文章

  1. Error response from daemon: You cannot remove a running container 8d6f0d2850250627cd6c2acb2497002fc3
  2. html标准模式,html如何使标准模式工作和怪癖模式?_firefox_开发99编程知识库
  3. Stable Diffusion - Prompts 提示词的格式化 (酷女孩、赛博朋克、商务女性)
  4. 双态运维:如何让CMDB配置维护更贴近人性
  5. GTD3年来读的52本书
  6. 如何申请公司邓白氏编码(D-U-N-S Number)
  7. Windows 扩展 C 盘扩展卷按钮显示灰色怎么办
  8. 关于flask入门教程-ajax+echarts实现地图GDP展示
  9. MySQL8.0 相关汇总 不断完善 持续更新……
  10. 学会这几招,轻松提升办公效率