仅用1个按钮多次更改<p>的innerHTML

时间:2016-10-18 17:36:59

标签: javascript php jquery html

您好我正在尝试制作一步一步的说明,我希望效果就像当用户点击按钮时按钮内的单词STEP 1元素将更改为步骤1中的详细信息。之后,相同的按钮将按钮内的单词更改为步骤2,单击时将相同的p元素内容更改为步骤2指令是否可以使用javascrpt,jQuery或php? ?

4 个答案:

答案 0 :(得分:1)

您可以通过各种方式进行操作。您可以使用jquery或纯JavaScript。我建议采用以下逻辑:

1)初始化按钮带有第一步标签和一些跟踪步骤的变量(例如var step = 1 initial

<button>Step <span>1</span><button>

2)点击你增加变量,获取按钮中的范围并用该变量更新其内容。

这是fiddle

答案 1 :(得分:0)

您可以尝试使用简单的功能来执行此操作

 <!-- this is the Details Div -->
 <div id="stepDetails"> Step Details Here </div>
 <!-- here is your button that changes with onClick binding -->
 <button id="stepButton" onClick="next_step()"> Step 1 </div>
 <script> 
      /* global arrray with details */
      var step_details = ["Intro Details", "Step 1 Details", "Step 2 Details"];
      /* global variable to track position in array */
      var current_step = 0;

      /* function to be called from onClick binding */
      function next_step() {

              current_step++;   /* increase the step variable */


              document.getElementById("stepDetails").innerHTML = step_details[current_step];


              document.getElementById("stepButton").innerHTML = "Step " + (current_step + 1);
       }

</script>

编辑:添加了一些评论以帮助更好地解释代码

答案 2 :(得分:0)

是的,你可以用js或jquery创建它(也许它更好)。您可以简单地使用基本函数,例如&lt; ... onlick =“yourfunction()”&gt;改变步骤

<script type="text/javascript"> function youfunction(){

    document.getElementById("p").innnerHTML = 'myDetails';
    .....  


}</script>

答案 3 :(得分:0)

增加个数组索引:

 <body>
 
 
    <div id="div">sample text</div>
    <button id="button" onClick="next_step()"> Step 1 </div>
    
    
    <script> 

      let arr = ["step 1", "step 2", "step 3" , "sample text" ];

      let count = 0; // step

     function next_step() {
     
      if (count < 5) document.getElementById("div").innerHTML = arr[count];
           count++;
      if (count == 4) count = 0; // use 3 for stoping function on the last element
        
        }
   </script>
   
   
  </body>

,如果您想同时增加增加减少,则可以使用以下方法:

"use strict";

let arr = ["index0", "index1", "index2", "index3", "index4"];
let count = 0;
document.getElementById("div").innerHTML = arr[0];
function getup() {
  if (count < arr.length) count++;
  if (count === arr.length) count = 0;
  document.getElementById("div").innerHTML = arr[count];
}
function getdown() {
  if (count >= 0) count--;
  if (count === -1) count = arr.length - 1;
  document.getElementById("div").innerHTML = arr[count];
}
<div id = "div"></div>
<button onclick = "getup()">up</button>
<button onclick= "getdown()">down</button>

相关问题