如何在所有onClick事件完成后继续进行?

时间:2016-11-03 17:32:06

标签: javascript jquery highcharts onclick

我有一个HighCharts lib包装器,它基于their API自动生成一些代码。为了自动生成这个代码,我必须导出API网站的HTML,用ALL(递归)扩展链接(从左侧菜单)。这必须以递归方式完成,因为新的扩展链接可能具有更多尚未扩展的链接。

现在我必须手动从浏览器的Javascript控制台继续此循环:

  1. $('div.collapsed').find($('a.plus')).click();
  2. $('div.collapsed').find($('a.plus')).length。如果为零,我就完成了。如果没有零,则再次进行1)。
  3. 我尝试将其自动化如下:

    while ( $('div.collapsed').find($('a.plus')).length !== 0 ) {
        console.log('Doing a pass');
        $('div.collapsed').find($('a.plus')).click();
        console.log('Pass finished');
    }
    

    但它无效,因为它进入无限循环。我想这是因为onClick会激发一些异步代码(也许是一个Ajax调用?)。任何想法我怎么能让它工作?

    提前致谢,

2 个答案:

答案 0 :(得分:1)

$('div.collapsed').find($('a.plus')).length不会更改值,请使用

$('div.collapsed').find('a.plus').each(function(){
//some code
})

了解有关每种情况的更多信息。请查看here

答案 1 :(得分:0)

我终于以这种方式修复了它:

/* Technically we could simulate the click on the links, like this:
$('div.collapsed').find($('a.plus')).click();
But that won't work as the clicks fire an async AJAX call so we don't know
when to expand their children. To make the recursion to work, I found there are many useful functions
in http://api.highcharts.com/resources/js/api.js
The function toogleExpand() allow us to pass a callback. That way, on callback, we expand again with children
making the recursion to work. */
function expandLinks( items ) {
    if (items.find('div[id$="-menu"]').length !== 0) {
        items.find('div[id$="-menu"]').each(function(){
            var link = $(this);
            toggleExpand(link.closest('.collapsed'),  function() {
          /* note that in this case we are making the recursion but only with the children of items */
          expandLinks( items.find('div.menuitem.collapsed') )
        });
            });
    } else {
    if( $('div.collapsed').find($('a.plus')).length == 0 ) {
      /* If there are no more links to open it means everything is ready so lets download the file */
      downloadDetailsDivContent();
    }
  }
}