我有一个回显一些元素的循环。我还有一个 if 语句,如果它包含来自数据库的某个字符串,则将复选框“checked”属性应用于复选框元素,例如:
if ($team == $row['team1']) {
$checked1 = "checked='checked'";
}
else {
$checked1 = "";
}
if ($team == $row['team2']) {
$checked2 = "checked='checked'";
}
else {
$checked2 = "";
}
echo "<div><input type='radio' name='games" . $i . "' value='" . $row['team1'] . "' " . $checked1 . "></div>";
echo "<div><input type='radio' name='games" . $i . "' value='" . $row['team2'] . "' " . $checked2 . "></div>";
这似乎工作正常。但我还想在复选框周围的 div 中添加一个类,例如:
if ($team == $row['team1']) {
$checked1 = "checked='checked'";
$div1 = "class='green'";
}
else {
$checked1 = "";
$div1 = "";
}
if ($team == $row['team2']) {
$checked2 = "checked='checked'";
$div2 = "class='green'";
}
else {
$checked2 = "";
$div2 = "";
}
echo "<div " . $div1 . "><input type='radio' name='games" . $i . "' value='" . $row['team1'] . "' " . $checked1 . "></div>";
echo "<div " . $div2 . "><input type='radio' name='games" . $i . "' value='" . $row['team2'] . "' " . $checked2 . "></div>";
问题是该类似乎将其自身应用于循环产生的所有 div。这是循环和回显元素的副产品吗?有没有更好的方法来实现这一点(也许使用 JQuery)。
编辑:添加了 HTML 结果
<div class='green'><input type='radio' name='games1' value='myteam' checked='checked'></div>"
<div><input type='radio' name='games1' value='yourteam' ></div>
<div class='green'><input type='radio' name='games1' value='myteam' ></div>"
<div><input type='radio' name='games1' value='yourteam' checked='checked'></div>
<div class='green'><input type='radio' name='games1' value='myteam' ></div>"
<div><input type='radio' name='games1' value='yourteam' checked='checked'></div>
<div class='green'><input type='radio' name='games1' value='myteam' checked='checked'></div>"
<div><input type='radio' name='games1' value='yourteam' ></div>"