Reputation: 719
i wrote this mini jquery snippet, but i want to get the id of the li element so i can post this data to an ajax call this is my script
$('#list li a').on('click', function(e) {
var id = ? //need to get li id
e.preventDefault();
$.ajax({
type: "POST",
url: "unfollow.php",
data: id,
success: function(){
$(this).parent().hide();
$('.updateNumber').html(function(){
return parseInt($(this).text(),10)+1;
});
}
});
});
});
this is an example html list:
<ul id="list">
<li id="list_1" class="list"><a href="">hide</a></li>
</ul>
thanks :)
Upvotes: 1
Views: 222
Reputation: 3909
$('#list li a').on('click', function(e) {
var id = $(this).parent("li").attr("id");
e.preventDefault();
$.ajax({
type: "POST",
url: "unfollow.php",
data: id,
success: function(){
$(this).parent().hide();
$('.updateNumber').html(function(){
return parseInt($(this).text(),10)+1;
});
}
});
});
});
Upvotes: 3
Reputation: 9680
Check this demo on jsFiddle.net. You will need to use .parent()
with $(this)
.
HTML
<ul id="list">
<li id="list_1">
<a href="#">Test Anchor One</a>
</li>
<li id="list_2">
<a href="#">Test Anchor Two</a>
</li>
</ul>
JavaScript
$('#list li a').on('click', function(e) {
var id = $(this).parent().attr("id").replace("list_", "");
alert(id);
});
This will give 1
or 2
as id
.
Hope this helps you.
Upvotes: 0
Reputation: 82287
For the number of list_n
use
var id = this.parentNode.id;
var number = id.substring(5);
Upvotes: 0
Reputation: 76880
You could use plain javascript (no need for the extra calls to jQuery)
var id = this.parentNode.id
fiddle here http://jsfiddle.net/rL29r/
EDIT - to get just the number
var id = this.parentNode.id.replace('list_', '')
Upvotes: 3
Reputation: 324640
id = this.parentNode.id;
This is at least 8 times faster than the jQuery equivalent. Don't use jQuery for something so simple.
Upvotes: 1
Reputation: 262939
Since the <a>
elements you're matching are descendants of <li>
elements, and you seem to be wanting the id
of the ancestor <li>
element, you can use the closest() method:
var id = $(this).closest("li").attr("id");
Upvotes: 1