在点击PHP时显示数组值

Display array value on click PHP

本文关键字:显示 数组 PHP      更新时间:2023-09-26

让我们开始吧!

我做了一个PHP计算,我不想在我的网站上显示。棘手的部分是,我想要显示的值,一个值,每次用户单击一次按钮。不管它是什么类型的按钮,我只是不想在每次点击时显示一个值。值的总数是8(固定长度),现在我有4个数组,每个数组中有2个值。所有东西都完成并保存了,我只是想一次显示一个。如果更简单的话,我可以把它们组合成一个数组。我试图使一种display:none vs显示onclick的东西,但它只显示每次点击的第一个值。非常感谢你的提示和技巧!一种FORM对我有帮助吗?用input代替?

这是我得到的:

HTML

<a href="#" class="modern" onClick="showhide('first', 'block'); return false" >Give me your value</a>
<div id="first"><?php echo $team1[0];?></div>
<div class="secound"><?php echo $team1[1];?></div>
<div class="third"><?php echo $team2[0];?></div>
<div class="fourth"><?php echo $team2[1];?></div>
...
Javascript

function showhide(divid, state){
 document.getElementById(divid).style.display=state
}

有很多不同的方法可以做到这一点。使用框架会让你更容易、更轻松地支持多个浏览器,但假设这不是你的目标,并坚持尽可能多地使用…

我已经改变了一点PHP:

<a href="#" id="team-next">Give me your value</a>
<div id="teams">
  <div id="team-0"><?= $team[0][0] ?></div>
  <div id="team-1"><?= $team[0][1] ?></div>
  <div id="team-2"><?= $team[1][0] ?></div>
  <div id="team-3"><?= $team[1][1] ?></div>
  ...

请注意,我已经将id更改为前缀team-和索引0…N,并且团队出现在id为teams的父元素中。我还将数组更改为多维数组,而不是包含数字的多个变量。此构造可以通过将数组添加为数组的项来创建。现在JavaScript(它应该出现在上面HTML之后的script标签中):

// Initial index -1 (nothing displayed)
var current = -1;
// How many teams are there?
var count = document.getElementById("teams").children.length;
// The handler
function showNext() {
  // A bit of modulus math, when it gets to the
  // same value as the count it starts at 0 again
  var next = (current + 1) % count;
  // Hide the previous one, unless it is the first
  if(current !== -1)
    document.getElementById("team-" + current).removeAttribute("style");
  // Show the next one
  document.getElementById("team-" + next).style.display = "block";
  // Update the current index
  current = next;
} 
// Bind the event listener
document.getElementById("team-next").addEventListener("click", showNext, false);

Here is a fiddle