如何隐藏/显示从PHP生成代码的HTML元素的可见性?

时间:2016-08-13 20:51:07

标签: javascript php html

我需要在代码中隐藏/显示HTML元素。 该页面是用PHP生成的。

试图在这里简化我的代码,你可以找到一个展示我麻烦的样本......

echo '<button type="button" onclick="hide_show('.$n_images.')">Hide / show details</button>';

echo '<script  language="javascript">';
echo 'function hide_show(n_images)';
echo '  {';
echo '     element = document.getElementById("details_0");';
echo '     if (element.style.visibility == \'visible\') {';
echo '      element.style.visibility = \'hidden\'';
echo '     }';
echo '     else {';
echo '      element.style.visibility = \'visible\'';
echo '     }';
echo '  }';
echo '</script>';

在这种情况下,代码正常运行,一切正常。

我的问题是我有几个要隐藏/显示的元素,所以我需要替换

echo '     element = document.getElementById("details_0");';

使用一段时间,我不知道该代码的概括......

我的最终代码应该是这样的......

echo '<button type="button" onclick="hide_show('.$n_images.')">Hide / show details</button>';

echo '<script  language="javascript">';
echo 'function hide_show(n_images)';
echo '  {';
echo '   while (current_index < n_images )  {';
echo '     element = document.getElementById("details_0");'; --> this is the line I need to generalize !!!
echo '     if (element.style.visibility == \'visible\') {';
echo '      element.style.visibility = \'hidden\'';
echo '     }';
echo '     else {';
echo '      element.style.visibility = \'visible\'';
echo '     }';
echo '     current_index = current_index + 1;';
echo '   }';
echo '  }';
echo '</script>';

任何帮助/建议/示例?

提前谢谢!

切萨雷

1 个答案:

答案 0 :(得分:1)

嗨Cesare让你更容易为什么不只是为你的整个JavaScript使用一个php echo语句。在你的while循环之前,在你需要概括的行中的js中将current_index初始化为0. getElementById(“details_”+ current_index)