简体   繁体   English

如何在laravel刀片上循环动态添加“活动”类? (Laravel 5.3)

[英]How do I add 'active' class dynamically in loop on the laravel blade? (Laravel 5.3)

My view is like this : 我的看法是这样的:

<ul class="nav nav-tabs nav-cat">
    @foreach($countries as $country)
        <li role="presentation"><a href="javascript:;" data-toggle="tab" @click="$refs.player.getPlayer({{ $country->id }})">{{ ucfirst($country->name) }}</a></li>
    @endforeach
</ul>

I want add class="active" in li tag. 我想在li标签中添加class="active" So, when the tab clicked, the li tag will active. 因此,单击选项卡时,li标签将处于活动状态。 And I want first loop will active too 我希望第一个循环也能活跃

How can I do it? 我该怎么做?

If you will follow instructions about The Loop Variable you will find usefull $loop->first helper. 如果您遵循有关循环变量的说明 ,则会发现有用的$ loop-> first helper。 It returns true if it's first item in an array. 如果它是数组中的第一项,则返回true。 So you can do this: 因此,您可以执行以下操作:

@foreach($items as $item)
    <li class="{{ $loop->first ? 'active' : '' }}">...</li>
@endforeach

Then on tab class click if you want to move class to active tab you should make it by using javascript 然后在选项卡类上单击,如果您想将类移动到活动选项卡,则应使用javascript进行设置

You could use javascript to do this also! 您也可以使用javascript来做到这一点!

  1. Set an ID to your li tag. 为您的li标签设置一个ID。
  2. Get your li tag element by the id. 通过id获取您的li标签元素。
  3. .addClass('active');

I have used a laravel package in the past if you need a quick fix 如果您需要快速修复,我过去曾使用过laravel软件包

https://github.com/dwightwatson/active https://github.com/dwightwatson/active

Just Use $loop->first active in your li class. 只需在li类中使用$ loop-> first active即可。 class="{{ $loop->first ? 'active' : '' }}"

Sample example:- 示例示例:-

@foreach ($category as $v_cat)
<li class="{{ $loop->first ? 'active' : '' }}"><a href="#{{$v_cat->category_name}}" data-toggle="tab">{{$v_cat->category_name}}</a></li>
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM