问题 当reveal.js中出现某个幻灯片时执行函数


我用这个javascript框架创建了一个演示文稿 http://lab.hakim.se/reveal-js/#/ 当某个幻灯片出现时,我想执行函数stats(),它每隔5秒显示一次来自API的数据,但只有当这张幻灯片出现时才会显示

function stats(){                
$.ajax({
    type: "GET",
    url: url_survey,
    dataType: "json",
    success : 
      function (data) {
      //some code to display data       
    },
    error:
      //some code
}); 
}

在HTML文件中我有这个:

<section>
<div id="stats">
</div>
</section>

我该怎么做?我写了这段代码,但它始终有效,不仅在幻灯片出现时

function check(){
if($("#stats").is(":visible"))
stats();
}

check();
setInterval(function(){check()}, 2000);

8508
2018-03-02 21:29


起源



答案:


这可以通过使用reveal.js状态来实现(https://github.com/hakimel/reveal.js#states)。

1)向应该触发方法的部分添加一个唯一的状态。

<section data-state="stats">
    <h2>This will trigger a state event with the name "stats".</h2>
</section>

2)使用reveal.js API将侦听器添加到自定义状态。

Reveal.addEventListener( 'stats', function() {
    // Called each time the slide with the "stats" state is made visible
} );

完整的工作示例: https://gist.github.com/hakimel/cea4305a33713d4a5a7e


14
2018-05-08 10:39



是的,但我需要用HTML格式:<section> <div id =“stats”> </ div> </ section> ...是否有其他解决方案如何在外部js文件中创建它@hakim - user3357400
很酷,是否可以将参数传递给事件处理函数?谢谢 - Philippe


答案:


这可以通过使用reveal.js状态来实现(https://github.com/hakimel/reveal.js#states)。

1)向应该触发方法的部分添加一个唯一的状态。

<section data-state="stats">
    <h2>This will trigger a state event with the name "stats".</h2>
</section>

2)使用reveal.js API将侦听器添加到自定义状态。

Reveal.addEventListener( 'stats', function() {
    // Called each time the slide with the "stats" state is made visible
} );

完整的工作示例: https://gist.github.com/hakimel/cea4305a33713d4a5a7e


14
2018-05-08 10:39



是的,但我需要用HTML格式:<section> <div id =“stats”> </ div> </ section> ...是否有其他解决方案如何在外部js文件中创建它@hakim - user3357400
很酷,是否可以将参数传递给事件处理函数?谢谢 - Philippe


回答Philippe Leefsma的问题:你可以使用bind()传递参数,如下所示:

drawDiagramOnSlide.bind(
    null,
    slideName,
    slideEl.querySelector('.diagram')
));

假设drawDiagramOnSlide看起来像这样:

function drawDiagramOnSlide(_slideName, _diagramEl, _event) {...}

bind调用将创建一个函数,该函数使用正确的幻灯片名称和元素调用drawDiagramOnSlide(在我的例子中,幻灯片中包含类图的div)。


0
2017-07-11 11:01