jQuery 如何使用jquery获取html列表项的id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8187597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the id of html list item using jquery?
提问by NinjaBoy
I wanna get the id of <li>
using jquery. I was able to get the text using alert($(this).text())
but when I tried alert($(this).id())
it says undefined
.
我想获得<li>
使用 jquery的 id 。我能够使用文本,alert($(this).text())
但是当我尝试时alert($(this).id())
它说undefined
.
<html>
<head>
<style type="text/css">
ul {
list-style-type: none;
}
</style>
<script type="text/javascript" src="jquery1.6.4min.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$('#list li').click(function() {
alert($(this).id());
alert($(this).text());
});
});
</script>
</head>
<body>
<ul id="list">
<li id="l1">Value 1</li>
<li id="l2">Value 2</li>
<li id="l3">Value 3</li>
<li id="l4">Value 4</li>
<li id="l5">Value 5</li>
<li id="l6">Value 6</li>
<li id="l7">Value 7</li>
<li id="l8">Value 8</li>
<li id="l9">Value 9</li>
<li id="l10">Value 10</li>
<li id="l11">Value 11</li>
<li id="l12">Value 12</li>
</ul>
</body>
</html>
Plase help me with this. Thanks in advance.
请帮我解决这个问题。提前致谢。
回答by Clive
回答by Tesserex
it's actually $(this).attr('id')
, not $(this).id()
.
它实际上$(this).attr('id')
,不是$(this).id()
。
回答by Dallas
id is an attribute. You need
id 是一个属性。你需要
alert($(this).attr('id'))
回答by Icarus
回答by TechnicalKalsa
You can use jQuery 1.6 + then you should use this code.
您可以使用 jQuery 1.6 + 然后您应该使用此代码。
var id = $(this).prop('id');