For example, I would like to add class ' active
' to LI
that have class' list-1
' when user clicks anchor tag which have class ' link-1
' and remove class ' active
' from other lists. Same case applies further. Any suggestion would be very helpful.
<br>
<br>
<ul class="list-item">
<li class="list-0 active">Product One</li>
<li class="list-1">Product Two</li>
<li class="list-2">Product Three</li>
<li class="list-3">Product Four</li>
</ul>`
<br>
<br> `
<div class="pager-list">
<a href="#" class="link-0">1</a>
<a href="#" class="link-1">2</a>
<a href="#" class="link-2">3</a>
<a href="#" class="link-3">4</a>
</div>
Try the following:
$(".pager-list").find("a").on("click", function(e) { e.preventDefault(); var value = $(this).data("value"); $(".list-item") .find(".list-" + value).addClass("active") .siblings().removeClass("active"); });
<ul class="list-item"> <li class="list-1 active">Product One</li> <li class="list-2">Product Two</li> <li class="list-3">Product Three</li> <li class="list-4">Product Four</li> </ul> <div class="pager-list"> <a href="#" data-value="1">1</a> <a href="#" data-value="2">2</a> <a href="#" data-value="3">3</a> <a href="#" data-value="4">4</a> </div>
<ul class="list-item">
<li class="list-0 active">Product One</li>
<li class="list-1">Product Two</li>
<li class="list-2">Product Three</li>
<li class="list-3">Product Four</li>
</ul>
<div class="pager-list">
<a href="#" class="link-0" data-rel="list-0">1</a>
<a href="#" class="link-1" data-rel="list-1">2</a>
<a href="#" class="link-2" data-rel="list-2">3</a>
<a href="#" class="link-3" data-rel="list-3">4</a>
</div>
<script>
$('.pager-list').on('click', 'a', function(e){
e.preventDefault();
$('.list-item li').removeClass('active');
$('.list-item li.'+$(this).data('rel')).addClass('active');
});
</script>
or alternatively (without data-, but then order of the links and order of the list items is important)
<ul class="list-item">
<li class="list-0 active">Product One</li>
<li class="list-1">Product Two</li>
<li class="list-2">Product Three</li>
<li class="list-3">Product Four</li>
</ul>
<div class="pager-list">
<a href="#" class="link-0">1</a>
<a href="#" class="link-1">2</a>
<a href="#" class="link-2">3</a>
<a href="#" class="link-3">4</a>
</div>
<script>
$('.pager-list').on('click', 'a', function(e){
e.preventDefault();
var links = $('.pager-list a');
$('.list-item li').removeClass('active');
$('.list-item li').eq(links.index(this)).addClass('active');
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.