【问题标题】:Accessing nth-child using id in angular在角度中使用 id 访问第 n 个孩子
【发布时间】:2026-02-10 06:15:02
【问题描述】:

我正在尝试使用代码美化为特定行着色。我正在从后端获取行号方面的数据,并希望突出显示它们。 如果我在我的 css 文件中写这个:

#file2 li:nth-child(n+1):nth-child(-n+11) {
        background: #18b478;
    }

它工作正常。但是,我无法弄清楚如何使用 angular 来实现这一点,我想根据我得到的行号动态地对 CSS 进行更改。这是我尝试过的:

$("#file2 li:nth-child(n+1):nth-child(-n+11)").css('background', "#18b478");

这是我的html代码:

<div class="container" style="margin-bottom: 50px">
<div class="col-sm-6">
    <pre>
        <code class="prettyprint linenums" id="file1">***some code***</code>
    </pre>
</div>

【问题讨论】:

  • 使用 Angular 通常意味着不要使用 jQuery
  • 希望 li:nth-child(n+1) 选择每个 li。我对这个选择器有点困惑!

标签: javascript jquery css angularjs google-code-prettify


【解决方案1】:

假设您在数组中有线条颜色。 (具有行数的长度)并且您将行放在另一个数组中。

$scope.lines = linesarray
$scope.colors = colorsarray

在代码中

<pre>
    <code ng-repeat="line in $scope.lines">
        Line content: {{ line }}
        Line number is: {{ $index }}
        Associated color is: {{ colors[$index] }}
    </code>
    //make use of the $index that returns current index of the ng-repeat loop
</pre>

希望这会有所帮助!

【讨论】: