网络编程
位置:首页>> 网络编程>> JavaScript>> jquery中获取id值方法小结

jquery中获取id值方法小结

作者:mdxy-dxy  发布时间:2024-04-19 10:19:25 

标签:jquery获取id

先判断是jquery对象还是html对象, 如果是jquery对象, 可以直接用 jquery对象.attr("id")获取

 如果是html对象,可以用 html对象.id 或者 $(html对象).attr("id")

一般来说 $("#id").val()或者

下面脚本之家小编就整理一下常用几种获取方式

例如页面内容如下

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>jquery获取id值—asp之家</title><script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js"></script></head><body><div id="asp"><a href="https://www.aspxhome.com">asp之家</a></div><div id="asptxt">脚本之家</div><div class="aspclass">脚本之家</div><input type="text" value="aspnet" class="okasp" /><script>var title=$('title').text(); console.log(title);//因为title是标签不用加 .或者 #var idasp=$('#asp').html();//id使用#var idasptxt=$('#asptxt').html();</script></body></html>

测试

$('#asp').html()//'<a href="https://www.aspxhome.com">asp之家</a>'$('#asp').text()//'asp之家'

如果只想获取文字就用 

$('#asp').text()'asp之家'

如果想获取里面的html元素就用

$('#asp').html()'<a href="https://www.aspxhome.com">asp之家</a>'

id与classj就是.与#的区别,但一般来说class都是复用的,需要判断究竟要第几个。

如果是想获取页面中的制定id或者一些自定义属性值就需要用attr、prop、data等方式,具体的可以参考这篇文章

jQuery 获取与设置 元素属性

<div id="product"> </div><script language = "JavaScript" type="text/javascript">$(document).ready(function(){name = $('div').eq(0).attr('id');alert(name)});

eq(0)是取第一个jq元素。。。

eq(index)匹配一个给定索引值的元素

Matches a single element by its index.返回值Element

参数index (Number) : 从 0 开始计数

示例查找第二行

HTML 代码:

<table><tr><td>Header 1</td></tr><tr><td>Value 1</td></tr><tr><td>Value 2</td></tr></table>

jQuery 代码:

$("tr:eq(1)")

结果:

[ <tr><td>Value 1</td></tr> ]

获取不同id的值

<script src="js/jquery.js"></script><script type="text/javascript"><!--$(document).ready(function(){var len = $("#group span").size();//获取span标签的个数var arr = [];for(var index = 0; index < len-1; index++){//创建一个数字数组arr[index] = index;}$.each(arr, function(i){//循环得到不同的id的值var idValue = $("#group span").eq(i).attr("id");if(idValue != ''){alert(idValue);}});});//--></script><span id="group"><span id="0_1">aaa,<span group_id="0_1" class="icon_close">&nbsp;</span></span><span id="0_2">bbb,<span group_id="0_2" class="icon_close">&nbsp;</span></span><span id="0_3">ccc,<span group_id="0_3" class="icon_close">&nbsp;</span></span><span id="0_4">ddd,<span group_id="0_4" class="icon_close">&nbsp;</span></span><span id="0_5">eee,<span group_id="0_5" class="icon_close">&nbsp;</span></span></span>

这样就会得到你想要的所有的id:

0_10_20_30_40_5

文本框,文本区域:

$("#txt").attr("value",'');//清空内容$("#txt").attr("value",'11');//填充内容

多选框checkbox:

$("#chk1").attr("checked",'');//不打勾$("#chk2").attr("checked",true);//打勾if($("#chk1").attr('checked')==undefined) //判断是否已经打勾
0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com