使用 jQuery 多次更改 DIV 文本


Change DIV text with jQuery multiple times

我有以下代码:

<h2 id="excTitle">
   <div id="titleText">
       <?=$exercises[$currentExc]?>
   </div>
</h2> 

上面的代码显示一个标题。

<button type="button" class="styled-button-10b" onClick="skipExc()">Skip</button>

上面的代码调用下面的函数,该函数应该更改标题。

//Skip to the next exercise
function skipExc()
{
    <?php
         $currentExc++;
    ?>
    $("#titleText").html('<?php echo $exercises[$currentExc]; ?>');
}

它实际上有效,但只有一次。

假设我有 5 个不同的标题(我的 $exercises 数组中有 5 个项目),上面的代码只从第一个标题转到第二个标题,然后停止更新。

我已经测试过并调用了该函数,但标题没有改变。

有人可以帮我解决这个问题吗?谢谢。

您可以将 php 数组编码为 json,然后通过 javascript 更新计数器/索引

var count = 0;
        
function skipExc() {
  var exercises = <?php echo json_encode($exercises); ?>;
            
  $("#titleText").html(exercises[count]);
        
  count++;
}
<h2 id="excTitle">
  <div id="titleText"></div>
</h2>
<button type="button" class="styled-button-10b" onClick="skipExc()">Skip</button>
<?php $exercises = array('a', 'b', 'c'); ?>