当last_value_row元素的第一个td中的目标值是“新目标”时,我尝试向表单中的tr元素(last_value_row)添加一个类。 到目前为止,只有第一个元素会添加该类,而不是目标值为“新目标”的所有其他元素。
这是我的 HTML 端:
<table id="epoch_forms_table" class="epoch_forms_table">
<tr class="title_row">
<th>{% autoescape off %}{% trans "Target name" %}{% endautoescape %}</th>
...
<th class="last"></th>
</tr>
<tr class="value_row{% if epoch_form.errors %} error{% endif %}">
<td></td>
<td><label><input type="number" size="13" step="0.001"></label></td>
<td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td>
<td><a href="#" class="button icon remove remove_row_button danger"></a></td>
</tr>
<tr id="last_value_row" class="last_value_row target_background_color">
<td></td>
<td></td>
<td class="{{ key }}_unit unit" id="{{ key }}">{{ value }}</td>
<td></td>
</tr>
<tr class="error_row">
{% for field in epoch_form %}
<td>{{ field.errors }}</td>
{% endfor %}
<td></td>
</tr>
</table>
这是我的 JavaScript 端:
var new_target_element = document.getElementById("last_value_row");
var last_values = [];
var index = $("#epoch_forms_table tr.value_row").index(value_row);
...
for (let i = 0; i < el.length; i++) {
for (let i = 0, cell; cell = new_target_element.cells[i]; i++) {
if ($(this).find("td:contains('New target')")) {
new_target_element.classList.add("new_target_color");
new_target_element.classList.remove("target_background_color");
} else {
new_target_element.classList.add("target_background_color");
new_target_element.classList.remove("new_target_color");
}
}
}
if (last_values[index].length === 0) {
last_value_row.find("td:first").html("New target");
} else {
...
}
}
当第一个 td 中存在或不存在目标值“New Target”时,我尝试向每个“last_value_row”添加或删除 CSS 类“new_target_color”。到目前为止,只有第一个元素总是会改变它的类。
我认为你的 ID 为last_value_row的行有点转移注意力,你实际上想要找到具有此类的行(否则你正在寻找一系列唯一值,或者进入第n个子区域).
// Select all rows with class 'last_value_row'
var lastValueRows = document.querySelectorAll('.last_value_row');
// Function to add or remove classes based on the content
function updateRowClasses(row) {
// Check if the first cell contains 'New Target'
var isFirstCellNewTarget = row.cells[0].textContent.trim() === 'New Target';
// Add or remove classes based on the condition
if (isFirstCellNewTarget) {
row.classList.add("new_target_color");
row.classList.remove("target_background_color");
} else {
row.classList.remove("new_target_color");
row.classList.add("target_background_color");
}
}
// Iterate over each 'last_value_row' and apply the function
lastValueRows.forEach(updateRowClasses);