使用jQuery修改classList



我在更改表行的类时遇到问题。

我的HTML

<table class="table table-light table-bordered text-center">
<thead class="thead-dark">
<tr>
<th scope="col">Ava</th>
<th scope="col">Full name</th>
<th scope="col">Registred</th>
</tr>
</thead>
<tbody>
{{#users}}
<tr class="table-light" id="colorised">
<td><img src="{{avaUrl}}" width="42" height="42"/></td>
<td><a href="users/{{_id}}" style="margin-top: 50px;">{{username}}</a></td>
<td>{{registeredAt}}</td>
</tr>
{{/users}}
</tbody>
{{^users}}
</br>
<strong style="color: orange">No results for "{{searchedUsername}}"</strong>
</br>
</br>
{{/users}}
</table>

和JavaScript

<script>
$('#colorised').attr('class','table-success');
</script>

我怎样才能改变桌子那一排的颜色?

您可以在类之间切换以切换它们:

$('#colorised').toggleClass('table-light table-success');

要在DOM加载完成后执行代码,以便可以访问或修改,需要将jQuery代码封装在$(document).ready(function() {});中。假设您的代码位于DOM元素之前,例如在标记中,或者在某些DOM元素之前的部分的顶部或中间,并且该代码在第一次初始化时确实尝试访问DOM。

因此,它应该被放在$(document).ready()块中,这样它就不会在DOM准备好之前执行。$(document).ready()的缩写是$(function() {});。以下是您提供的代码示例。

$(function() {
$('#colorised').attr('class','table-success');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-light table-bordered text-center">
<thead class="thead-dark">
<tr>
<th scope="col">Ava</th>
<th scope="col">Full name</th>
<th scope="col">Registred</th>
</tr>
</thead>
<tbody>
{{#users}}
<tr class="table-light" id="colorised">
<td><img src="{{avaUrl}}" width="42" height="42"/></td>
<td><a href="users/{{_id}}" style="margin-top: 50px;">{{username}}</a></td>
<td>{{registeredAt}}</td>
</tr>
{{/users}}
</tbody>
{{^users}}
</br>
<strong style="color: orange">No results for "{{searchedUsername}}"</strong>
</br>
</br>
{{/users}}
</table>

最新更新