我的代码
<script type="text/javascript">
if(<?php echo json_encode($re=='reject'); ?>){
//if response is reject
document.getElementById('hide').style.display = "none";
document.getElementById('onreject').style.display="block";
}
else if(<?php echo json_encode($re=='approve'); ?>){
//if response is approve
document.getElementById('hide').style.display = "none";
document.getElementById('onapprove').style.display = "block";
}
else
{
document.getElementById('hide').style.display="block";
}
</script>
我希望这个在while循环中<?php $responseanswer = mysqli_fetch_array($result); ?>
我是怎么做到的?
答案 0 :(得分:2)
为了扩展第一个答案,这里有一个可能的解决方案,它不涉及在JavaScript和PHP之间来回切换太多。我个人喜欢模板引擎(例如Smarty),但这是我的下一个偏好(所有逻辑在PHP代码中,JavaScript在循环结束时只是显示为你工作)。
<script>
<?php
while($responseanswer = mysqli_fetch_array($result)) {
// This is probably not how your code does it, but I don't know your table structure
$re = $responseanswer[0];
$div_to_show = "";
// whether to show the element with ID "hide"
$hide_display_style = 'none';
// Decide now what divs we want visible and hidden
if($re == 'reject') $div_to_show = 'onreject';
else if($re == 'approve') $div_to_show = 'onapprove';
else $hide_display_style='block';
echo "document.getElementById('hide').style.display = '$hide_display_style';\n";
if($div_to_show) {
echo "document.getElementById('$div_to_show').style.display = 'block';\n";
}
}
?>
</script>
答案 1 :(得分:0)
你是说这个吗?
无论如何,在我看来,像这样结合JavaScript和PHP是不可取的。
<?
while($responseanswer = mysqli_fetch_array($result)) {
?>
if(<?php echo json_encode($re=='reject'); ?>){
//if response is reject
document.getElementById('hide').style.display = "none";
document.getElementById('onreject').style.display="block";
}
else if(<?php echo json_encode($re=='approve'); ?>){
//if response is approve
document.getElementById('hide').style.display = "none";
document.getElementById('onapprove').style.display = "block";
}
else
{
document.getElementById('hide').style.display="block";
}
<?
}
?>
答案 2 :(得分:0)
EWWW。这使得它很难阅读,我认为像这样的解决方案会更好。 (但不是最好的)。 Best可能会有一个知道如何处理隐藏和显示内容的js函数,或者自己在标记元素中添加样式或者不显式输出id。
无论哪种方式,这应该更具可读性,并且更容易添加其他元素;
<?php
switch ($re) {
case 'reject':
$styles = array(
'hide' => 'none',
'onreject' => 'block',
'onapprove' => 'none'
);
break;
case 'approve':
$styles = array(
'hide' => 'none',
'onreject' => 'none',
'onapprove' => 'block'
);
default:
$styles = array(
'hide' => 'block',
'onreject' => 'none',
'onapprove' => 'none'
);
}
foreach ($styles as $id => $value) {
echo 'document.getElementById("' , $id, '").style.display="', $value, '";', PHP_EOL;
}
?>