我有一个包含一些帖子类别的菜单:
<ul>
@foreach($categories->get() as $category)
<li class="ative">
<a href="#" name="category" id="{{$category->id}}">{{$category->name}}</a>
</li>
@endforeach
</ul>
当我点击类别时,例如ID&#34; 1&#34;,通过菜单,它会在#posts div中显示属于id&#34; 1&#34;的类别的帖子
问题:
它工作正常,问题是,起初我想要第一类与#34;活跃&#34;。但是当点击另一个类别时,我想显示该类处于活动状态的点击类别。但是不是那样工作,当页面被激活时,所有类别都是活动的,并且当点击另一个类别时,所有类别都是活动的。你知道如何纠正这个问题吗?
#posts div显示首次访问页面时的最后一些帖子:
<div id="posts">
@foreach($posts as $key => $post)
<div id="post" + {{$key}}>
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
@endforeach
</div>
jQuery代码:
$("a[name='category']").on('click', function(){
//tried this by given answer which not worked
var category_id = $(this).attr("id");
('.categories li').removeClass('active');
$(this).addClass('active');
//ended code
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
var newPosts = "";
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' + + '<h1>' + post.title + '</h1>';
});
$('#posts').html(newPosts);
}, error: function(error) {
console.log(error.status)
}
});
});
答案 0 :(得分:1)
您需要在click
事件处理程序
$('ul li').removeClass('active');// remove active class from li
$(this).parent('li').addClass('active'); // add active class to current clicked li