这是我的php代码: -
echo'<li><input type="radio" id="option1" name="option1" onclick="myFunction()" required value="'.$option_id1.'">'.$option1.'</li>
<br /><br />';
echo'<li><input type="radio" id="option2" name="option2" onclick="myFunction()" required value="'.$option_id2.'">'.$option2.'</li>
<br /><br />';
这是我的JavaScript代码: -
function myFunction() {
var var1 = document.getElementById("option1").value;
var var2 = document.getElementById("option2").value;
var var5 = "<?php echo $ans; ?>";
if(var5==var1)
{
document.getElementById("option1").style.color = "green";
}
else if(var5==var2)
{
document.getElementById("option1").style.color = "green";
}
}
从您的PHP代码中,我可以看到您正在使用""
您必须更改var var5 = "<?php echo $ans; ?>";
到
var var5 = '<?php echo $ans; ?>';
希望这有帮助
始终使用纯JavaScript代码。
PHP代码: -
echo'<li><input type="radio" id="option1" name="option1" onclick="myFunction()" required value="'.$option_id1.'">'.$option1.'</li>
<br /><br />';
echo'<li><input type="radio" id="option2" name="option2" onclick="myFunction()" required value="'.$option_id2.'">'.$option2.'</li>
<br /><br />';
echo'<input type="hidden" id="answer" name="answer" value="'.$ans.'">';
JavaScript代码: -
function myFunction() {
var var1 = document.getElementById("option1").value;
var var2 = document.getElementById("option2").value;
var var5 = document.getElementById("answer").value;
if(var5==var1) {
document.getElementById("option1").style.color = "green";
}
else if(var5==var2) {
document.getElementById("option2").style.color = "green";
}
}