[英]Passing a variable into a javascript function in PHP to make specific divs hide or show?
I am trying to create a simple FAQ page where the user clicks the question and the answer appears below it (or hides it, if clicked again).我正在尝试创建一个简单的常见问题解答页面,用户单击问题并在其中显示答案(或隐藏它,如果再次单击)。
I got it working up to a point where all the questions will show the answer labeled "ans1".我让它工作到所有问题都会显示标记为“ans1”的答案。 But I would like to pass a variable from each question into the function so it makes the associated answer appear.
但我想将每个问题中的一个变量传递到函数中,以便显示相关的答案。 Question 1 will show Answer 1, Question 2 -> Answer 2, and so on.
问题 1 将显示答案 1、问题 2 -> 答案 2,依此类推。
My function...我的功能...
function theAnswer() {
var x = document.getElementById("ans1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
PHP... PHP...
<?php
$answer = 1;
foreach($faqArray as $faq) {
?>
<div class='product_container'>
<div class='product_cell'>
<a onclick="theAnswer()" href='#'>
<?php echo $faq[0];?>
</a>
</div>
</div>
<div class="answer" id="ans<?php echo $answer;?>" style="display:none;">
<p><?php echo $faq[1];?></p>
</div>
<?php
$answer = $answer + 1;
} ?>
If I put a variable in the onclick="theAnswer()" that dictates the associated div, how can I get the function to perform the desired result?如果我在 onclick="theAnswer()" 中放置一个变量来指示关联的 div,我怎样才能让函数执行所需的结果?
Thanks!谢谢!
Your PHP code is run server-side and your Javascript code is run client-side.您的 PHP 代码在服务器端运行,而您的 Javascript 代码在客户端运行。 So the two codes cant interact with each other.
所以这两个代码不能相互交互。 I recommend hiding your element with CSS use something like this:
我建议使用 CSS 隐藏您的元素,如下所示:
.hide{
display : none
}
and set your your div to hide like this并将您的 div 设置为像这样隐藏
<div class='hide' id='answer-<?php echo $answer;?>'> .... </div>
and you would remove hide from your element's class list like this你会像这样从元素的类列表中删除 hide
function theAnswer(num){
answer = document.querySelector('#answer-' + num)
answer.classList.remove('hide')
}
in your php code youd have to put in the value在您的 php 代码中,您必须输入值
.....
<a onclick="theAnswer('<?php echo $answer;?>')" href='#'>
.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.