为了检查表中的单元格是否包含javascript中的值,似乎我需要给每个td一个id。我将有数千个单元格,因此无法键入每个td及其id。
目前,带有所有 tds 的 trs 都是通过 html 中的循环生成的,因此使用 javascript 我想添加一个变量并将其粘贴在每个 id 的末尾。
我已经设法将一个 javascript 变量放入我的 html 循环中并且它正在正确计数,但我的问题是将其放入 id="___" 部分。
如下面的代码所示,我尝试将 document.write(i) 行放入 id 中,但它似乎将其视为普通文本。我还将其放在 DataEntryStatus 的输出中,只是为了证明它计数正确,从 1 开始,随着每一行新行的增加而增加。
<table class="table" id="table_id">
<tr>
<th style="color:#ddd">fffffffffffffff<br>f<br>f<br>f</th>
<th style="vertical-align:bottom;">Data Entry Status</th>
<th style="vertical-align:bottom;">Tool</th>
</tr>
<tbody id="myTable">
<script>
var i = 1;
</script>
{% for item in items %}
<tr>
<td>
<a href="{% url 'edit_newcuts' item.pk %}" class="btn btn-primary btn-sm" role="button">Edit</a>
<a href="{% url 'delete_newcuts' item.pk %}" class="btn btn-danger btn-sm" role="button">! X !</a>
</td>
<td id="DataEntryStatus"><div>{{ item.DataEntryStatus }} <script>document.write(i)</script></div></td>
<td id="Tool + <script>document.write(i)</script>"><div>{{ item.Tool }}</div></td>
</tr>
<script>
i = i + 1;
</script>
{% endfor %}
</tbody>
还有我的JavaScript:
$('#table_id tr').each(function(){
if($('#Tool' + 'i').text() =="")$('#DataEntryStatus' + 'i').text("Entry missing");
else if($('#CutRef' + 'i').text() =="")$('#DataEntryStatus' + 'i').text("Entry missing");
else($('#DataEntryStatus' + 'i').text("Complete"));
if($(this).text().toLowerCase() =="entry missing")$("#DataEntryStatus").css('background-color','#fcc');
if($(this).text().toLowerCase() =="complete")$("#DataEntryStatus").css('background-color','#af0');
});
我想要像我的id="Tool + document.write(i)"行这样的东西来制作像Tool1,Tool2,...但现在它将 + document.write(i) 视为普通文本,我不知道如何让它作为脚本工作。
看起来你正在使用 Django,那么为什么不使用它添加 ID?
<table class="table" id="table_id">
<tr>
<th style="color:#ddd">fffffffffffffff<br>f<br>f<br>f</th>
<th style="vertical-align:bottom;">Data Entry Status</th>
<th style="vertical-align:bottom;">Tool</th>
</tr>
<tbody id="myTable">
{% for item in items %}
<tr>
<td>
<a href="{% url 'edit_newcuts' item.pk %}" class="btn btn-primary btn-sm" role="button">Edit</a>
<a href="{% url 'delete_newcuts' item.pk %}" class="btn btn-danger btn-sm" role="button">! X !</a>
</td>
<td id="DataEntryStatus{{ forloop.counter0 }}"><div>{{ item.DataEntryStatus }}</div></td>
<td id="Tool{{ forloop.counter0 }}"><div>{{ item.Tool }}</div></td>
</tr>
{% endfor %}
</tbody>
Django 在循环中有一个forloop
变量,可以让你访问当前索引。
更新
要将其与 JavaScript 一起使用,请将counter
更改为counter0
。现在,这与 JavaScript 循环中的索引相同。
您可以通过像以前一样循环使用.each
来访问它,但稍作修改。
$('#table_id tr').each(function(i){
if($('#Tool' + i).text() =="")$('#DataEntryStatus' + i).text("Entry missing");
else if($('#CutRef' + i).text() =="")$('#DataEntryStatus' + i).text("Entry missing");
else($('#DataEntryStatus' + i).text("Complete"));
if($(this).text().toLowerCase() =="entry missing")$("#DataEntryStatus").css('background-color','#fcc');
if($(this).text().toLowerCase() =="complete")$("#DataEntryStatus").css('background-color','#af0');
});