jquery id from list items?
Ok, 开发者_StackOverflow中文版so i've got a list of usernames from the mysql database. But, i need the ID from the database so i was thinking something like this,
<li id='43'>Monica</li>
<li id='47'>Henrik</li>
<li id='77'>Eric</li>
But how can i get the ID from the list?
I would use something like the following:
<ul id="items-list">
<li id='member-43'>Monica</li>
<li id='member-47'>Henrik</li>
<li id='member-77'>Eric</li>
</ul>
then:
$('#items-list li').each(function() {
var id = $(this).attr('id').split('-')[1];
});
It was pointed out in the comments that as of HTML5 it's perfectly valid to start an id
attribute with a number, but I'd still give preference to this method, especially if there are to be multiple lists on a page from different DB tables (id
s still need to be unique). An id
of 43
has no meaning to anyone, but member-43
is much more clear.
Have a normal javascript on click event for the list element as shown below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
linkClicked = function (index) {
alert($('#myList li').get(index).id);
}
</script>
</head>
<body>
<ul id='myList'>
<li id='43' onclick="linkClicked($(this).index())">Monica</li>
<li id='47' onclick="linkClicked($(this).index())">Henrik</li>
<li id='77' onclick="linkClicked($(this).index())">Eric</li>
</ul>
</body>
</html>
This worked for me!
You could add a class with the same name to all of the list items
<li class="test" id='43'>Monica</li>
<li class="test" id='47'>Henrik</li>
<li class="test" id='77'>Eric</li>
Then you could use an on
$(".test").click(function(){
$(this).attr("id");
});
$('li').each(function(){
alert( $(this).attr('id') );
});
Try
$("li").eq(0).attr("id")
Substitute 0 by the index item of the list item you want to read the id of.
Do you actually want to do something with that id? There is too little data that you gave us. If you want to administer users you would need something like this:
<ul id="deleteUsers">
<li id='user43'><a href="deleteuser.php?id=43">Monica</a></li>
<li id='user47'><a href="deleteuser.php?id=47">Henrik</a></li>
<li id='user77'><a href="deleteuser.php?id=77">Eric</a></li>
</ul>
And than in jQuery override click event. roryf gave you good example.
You Can Use HTML5 Data Attribute in order to hold ID Data . Holding data in ID may give problem if you require to define id statically at some place so not an optimal solution You can check code below -
<li data-empid="A123" data-salary="120" class="datalist">Monica</li>
<li data-empid="A124" data-salary="121" class="datalist">Monica</li>
Access Data in Data Attribute in Jquery
<script type="text/javascript">
$( "li .datalist" ).click(function() {
$(this).data("salary")
});
</script>
精彩评论