Reputation: 184
Html
<ul>
<li>
<a href="" data-id="1" onclick="clickFunction();"></a>
</li>
<li>
<a href="" data-id="2" onclick="clickFunction();"></a>
</li>
<li>
<a href="" data-id="3" onclick="clickFunction();"></a>
</li>
<li>
<a href="" data-id="4" onclick="clickFunction();"></a>
</li>
<li>
<a href="" data-id="5" onclick="clickFunction();"></a>
</li>
</ul>
My app got a list of things then after 5secs. it will automatically go to the next li. but that is not the problem. the problem is with the click function I want to know the data-id of the li.
Upvotes: 0
Views: 518
Reputation: 6766
(1) Remove onclick
attribute.
(2) Attach a .click handler to all your links
$(function () {
// attach an onclick event handler to your links
$('li a[data-id]').click(function (e) {
// prevent the link from going anywhere
e.preventDefault();
// get the parent li
var li = $(this).closest('li');
// get next li's link data id
console.log(li.next('li').find('a').data('id'));
});
});
Upvotes: 0
Reputation: 33726
onclick attribute
.click
event using jQuery.closest('li')
to get the parent of your links.function clickFunction(e) {
e.preventDefault(); // This is to prevent the execution of your links!
console.log($(this).closest('li').data('id'));
}
$('a').click(clickFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-id="1">
<a href="">1</a>
</li>
<li data-id="2">
<a href="">2</a>
</li>
<li data-id="3">
<a href="">3</a>
</li>
<li data-id="4">
<a href="">4</a>
</li>
<li data-id="5">
<a href="">5</a>
</li>
</ul>
Upvotes: 1