简体   繁体   English

javascript:onclick转到特定的div

[英]javascript: onclick go to specific div

I'm trying to create a "diagram" with divs. 我正在尝试使用div创建一个“关系图”。 If user click on next it will show the next div and so on (this is done), but the thing i'm trying to reach is, sometimes some divs will have a question with "yes" or "no" buttons, and those buttons will target to some specific div. 如果用户单击“下一步”,它将显示下一个div,依此类推(完成此操作),但我要尝试达到的是,有时某些div会有“是”或“否”按钮的问题,而那些按钮将定位到某个特定的div。

Ex: Div 1 - Are you ok ? 例如:Div 1-您还好吗? Yes - Go to Div 2 | 是-转到Div 2 | No - Go to Div 3. 否-转到第3分部。

Is there a way to make this dynamic ? 有没有办法使这种动态? All divs have an ID. 所有div都有一个ID。

Here's the code i've got so far. 这是到目前为止我得到的代码。

HTML HTML

 <div id="main">   
  <h3 class="despistes">Some Title</h3>
      <div class="info" id="1" style="display:block">Div 1</div>
      <div class="info" id="2">Div 2</div>
      <div class="info" id="3">Div 3</div>
      <div class="info" id="4">Div 4</div>
      <div class="info" id="5">Div 5</div>
      <div class="info" id="6">Div 6</div>
      <div class="info" id="7">Div 7</div>
      <div class="info" id="8">Div 8</div>

 <button class="button" onclick="mostraDiv('inicio')" style="float:left">inicio</button>
 <button class="button" onclick="mostraDiv('avancar')" style="float:right">seguinte</button>
 <button class="button" onclick="mostraDiv('anterior')" style="float:right">retroceder</button>

</div>

JS JS

var divNo = 0;
function mostraDiv(direction) {
  var sel = document.getElementById('main').getElementsByTagName('div');
  for (var i=0; i<sel.length; i++) { sel[i].style.display = 'none'; }
  switch (direction) {
    case 'inicio' : divNo = 0; break;
    case 'anterior' : divNo--;   break;
    case 'avancar' : divNo++;   break;
    case 'ultima' : divNo = sel.length-1; break;

  }
  if (divNo > sel.length-1) { divNo = 0; }
  else { if (divNo < 0) { divNo = sel.length-1; } }
  sel[divNo].style.display = 'block';
}

onload = function() {
  mostraDiv('s');
};

This function i found here and works fine for me. 我在这里找到此功能,对我来说很好用。

Thanks in Advance. 提前致谢。

try this : 尝试这个 :

<p>Are You OK ?</p>
<button class="button" onclick="goToDiv(2)" style="float:left">Yes</button>
<button class="button" onclick="goToDiv(3)" style="float:left">No</button>

function goToDiv(divNo) {
  var sel = document.getElementById('main').getElementsByTagName('div');
  for (var i=0; i<sel.length; i++) { sel[i].style.display = 'none'; }
  if (divNo > sel.length-1) { divNo = 0; }
  else { if (divNo < 0) { divNo = sel.length-1; } }
  sel[divNo].style.display = 'block';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM