How to get the id of html list item using jquery?

落花浮王杯 提交于 2019-12-13 17:38:11

问题


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.

<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.


回答1:


You should get attributes from elements using the attr() function:

alert($(this).attr('id'));

The jQuery object doesn't have a method called id() which is why you're getting the result as undefined.




回答2:


it's actually $(this).attr('id'), not $(this).id().




回答3:


id is an attribute. You need

alert($(this).attr('id'))



回答4:


 $(document).ready(function() {
   $('#list li').click(function() {
    alert($(this).attr("id"));
    alert($(this).text());
   });
  });

Check jsfiddle here.




回答5:


You can use jQuery 1.6 + then you should use this code.

var id = $(this).prop('id');


来源:https://stackoverflow.com/questions/8187597/how-to-get-the-id-of-html-list-item-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!