我需要替换表的td中的文本,但是在特定条件下,我的表是使用DB的数据动态生成的,因此对行的生成没有限制。目前它只能使用一行因为id,但我尝试使用getElementByClassName,但谷歌Chrome表示该功能不存在。
这是我的表代码和我当前的JS Jquery代码:
<table class="table" id="table_headers">
<tr>
<th>Nombre</th>
<th>Correo</th>
<th>Curso inscrito</th>
<th style="text-align:center">Pagado</th>
</tr>
<?php
foreach($stmt->FetchAll() as $results) {
echo "<tr>";
echo '<td>' . $results['name'] . " " . $results['first_last_name'] . '</td>';
echo '<td>' . $results['user_email'] . '</td>';
echo '<td>' . $results['user_course'] . '</td>';
echo '<td id="user_pay">' . $results['user_pay'] . '</td>';
echo "</tr>";
}
?>
</table>
<script>
var pay = document.getElementById("user_pay").innerText;
if (pay == "0" ) {
console.log(pay);
$('#user_pay').html('No');
}else if(pay == "1"){
$('#user_pay').html('Si');
}
</script>
答案 0 :(得分:0)
这是一种jQuery方式。 我们将每个元素都具有“user_pay”类。 关于它的价值,我们编辑其内容。
(user_pay必须是一个类,因为id必须是唯一的。所以在代码的PHP部分中用id="user_pay"
替换class="user_pay"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="table_headers">
<tr>
<th>Nombre</th>
<th>Correo</th>
<th>Curso inscrito</th>
<th style="text-align:center">Pagado</th>
</tr>
<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">0</td></tr>
<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">1</td></tr>
<tr><td>name first_last_name</td><td>user_email</td><td>user_course</td><td class="user_pay">2</td></tr>
</table>
<script>
$(".user_pay").each(function( index ) {
if ($( this ).text()=="0") {
$( this ).html("No");
} else if($( this ).text()=="1") {
$( this ).html("Si");
}
});
</script>