0

我有一个回显一些元素的循环。我还有一个 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>"
4

2 回答 2

1

我怀疑问题出在您的循环上,但是我会尝试在您的逻辑之前声明变量。

这将确保它们每次都被清除:

$checked1 = "";
$div1 = "";
$checked2 = "";
$div2 = "";

if ($team ==  $row['team1']) {
  $checked1 = ' checked="checked"';
  $div1 = ' class="green"';
}

if ($team ==  $row['team2']) {
  $checked2 = ' checked="checked"';
  $div2 = ' class="green"';
}

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>';

此外,如果$team为空且$row[team1]为空,它将评估为真。

于 2013-03-08T00:56:56.860 回答
0

(我会发表评论,但我还没有足够的声誉。)

无论如何,你有这个理由吗:

$div1 ="class='green'";
$div2 ="class='green'";

? 当两个变量具有相同的值时,您所有的类看起来都一样。

于 2013-03-07T23:49:42.877 回答