我正在尝试在 stackoverflow 上调整其他具有类似问题的示例......但现在我很困惑。
这是我的 html 表格渲染后的样子:
<table class="table table-striped" id="status">
<thead>
<tr>
<th>Name</th>
<th>REP</th>
<th>Package</th>
<th> CV</th>
<th>Latest CV</th>
<th>Custom </th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>asfasdf</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="package">tmm</td>
<td>tmm-4.2.7-r1</td>
<td>4.2.7-r1</td>
<td> </td>
<td class="status_button"><button type="button" class="btn btn-success"></button></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="package">a-cis</td>
<td>a-cis-0.1.0-r0</td>
<td>0.1.0-r0</td>
<td> </td>
<td class="status_button"><button type="button" class="btn btn-danger"></button></td>
</tr>
</tbody>
</table>
我需要什么:
渲染表格后,我想找到所有具有危险按钮(“btn-danger”)的行,并将“Package”单元格/td 中的文本颜色更改为红色。
基于 stackoverflow 上的类似问题,这是我到目前为止所得到的:
122 <script>
123 $( document ).ready(function() {
124 $('.status_button').each(function(i, n) {
125 console.log($(n.innerHTML));
126 //somehow id the sibling <td> that has class
127 //package and change the font color
128 //to red
129 });
130 });
131
132 </script>
console.log 匹配对象中的属性并显示...但我的“if”语句失败。 我试图复制 console.log 的内容粘贴到此处,但尚未成功。
有关如何测试按钮类的值然后更改“包”字段中的文本颜色的任何提示,我们将不胜感激
谢谢。
编辑1
所以我更改了每个函数来查找 btn-danger 类...这似乎效果更好,因为它过滤了更多结果。 但我想我仍然需要帮助更改同级 td 与类“package”以显示红色文本。
122 <script>
123 $( document ).ready(function() {
124 $('.btn-danger').each(function(i, n) {
125 console.log($(n.innerHTML));
126 if ($(n.innerHTML) == "button.btn.btn-danger") {
127 alert('red!!');
128 };
129 });
130 });
131
132 </script>
最佳答案
您可以使用:has选择器来过滤具有您要查找的按钮的类 status_button 的所有单元格。
为了使用类包更改单元格的颜色,您可以使用 siblings .
代码片段:
$(function () {
$('.status_button:has("button.btn.btn-danger")').each(function(index, element) {
$(element).siblings('.package').css('color', 'red');
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table class="table table-striped" id="status">
<thead>
<tr>
<th>Name</th>
<th>REP</th>
<th>Package</th>
<th> CV</th>
<th>Latest CV</th>
<th>Custom</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>asfasdf</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="package">tmm</td>
<td>tmm-4.2.7-r1</td>
<td>4.2.7-r1</td>
<td> </td>
<td class="status_button">
<button type="button" class="btn btn-success"></button>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="package">a-cis</td>
<td>a-cis-0.1.0-r0</td>
<td>0.1.0-r0</td>
<td> </td>
<td class="status_button">
<button type="button" class="btn btn-danger"></button>
</td>
</tr>
</tbody>
</table>
关于javascript - jquery - 查找表中的元素并根据结果更改其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664274/