.first()元素不使用动态生成的<li>

时间:2015-09-03 06:24:44

标签: javascript jquery html angularjs spring

我想我在这里错过了一些小概念,但已经做了足够的谷歌搜索,但没有用。因此,在这个论坛上张贴寻求帮助。

我正在使用以下代码动态生成导航标签:

<div class="tabbable">  
 <ul class="nav nav-tabs"  id="testing">

   <li ng-repeat="storageOption in gridOptions[$index].ownedJay" class=""><a href="#c{{storageOption.StorageHostname}}" >Data{{storageOption.StorageHostname}}</a></li>


   </ul >

在上面的代码中,类留空。上面的代码可以根据storageOption(ng-repeat)中的元素数量创建许多li。

但是我想在第一个li中添加“active”类。 为此,我在同一页面的脚本部分添加了以下代码:

$(".tabbable ul li").first().addClass("active");    

但是上面的代码是在生成的所有li中添加活动类。

任何人都可以让我知道我在这里失踪的地方。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您需要以角度方式执行此操作,因为角度确实提供了ng-class的选项,基本上需要ng-class="{'class': expression}"这样的表达。在ng-class表达式中,您可以使用$first它会告诉您ng-repeat的第一个元素,并使用ng-href代替href

<强>标记

<li ng-repeat="storageOption in gridOptions[$index].ownedJay" ng-class="{'active': first}">
    <a ng-href="#c{{storageOption.StorageHostname}}" >Data{{storageOption.StorageHostname}}</a>
</li>

<强>替代

如果您想要激活切换,那么您可以简单地维护一个标志,该标志将包含选择li的信息。

<ul class="nav nav-tabs" id="testing" ng-init="selected=0">
    <li ng-repeat="storageOption in gridOptions[$index].ownedJay" 
      ng-class="{'active': $index == $parent.selected}" 
      ng-click="$parent.selected == $index">
        <a ng-href="#c{{storageOption.StorageHostname}}" >
          Data{{storageOption.StorageHostname}}
        </a>
    </li>
</ul >

在上面的标记中,我使用了$index,但如果你拥有ng-repeat数组,那么你可能是独一无二的。

答案 1 :(得分:1)

$(".tabbable").find('li:nth-child(1)').addClass("active");

尝试使用其他选择器选择第一个li

FIDDLE

答案 2 :(得分:0)

您可以使用ng-class属性检查$ index是否为0,然后添加class active。