2016-11-03 49 views
0

我有一個HighCharts自動生成一些代碼基於their API代碼包裝。爲了自動生成此代碼,我必須將所有(遞歸)鏈接(從左側菜單)的API網站的HTML導出爲已展開。這必須做遞歸,因爲新的擴展鏈接可能有更多尚未擴展的鏈接。如何在所有onClick事件完成後才能繼續?

現在我必須手動從瀏覽器的JavaScript控制檯繼續這個循環:

  1. $('div.collapsed').find($('a.plus')).click();
  2. $('div.collapsed').find($('a.plus')).length。如果爲零,我就完成了。如果沒有零,則繼續1)。

我想你完成這項類似如下:

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調用?)。任何想法我怎麼能使它工作?

由於提前,

+0

你所說的「擴大」是什麼意思? – guest271314

+0

每次點擊'a.plus'鏈接時,菜單'div.collapsed'都會顯示您擴展菜單的內部可能的新鏈接。你知道...該網站的3個點。這就是爲什麼我必須循環 –

+0

您是否按照@ pandeyvishal1986的建議嘗試使用'.each()'? – guest271314

回答

1

$('div.collapsed').find($('a.plus')).length是不會改變的價值,所以請使用

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

的每個方面的更多信息。請here

+0

謝謝,但我怎樣才能循環工作,並解決異步問題?當然,我可以做'$('div.collapsed')。find('a.plus')。each(function(){$(this).click();});'。但是這並不能解決這樣一個事實,即我必須多次迭代,直到沒有更多的'a.plus',並且可能'點擊'做的事情是異步的。 –

+0

您可以使用javascript的'setInterval'函數在特定的時間間隔內執行操作。請參考[鏈接](http://www.w3schools.com/jsref/met_win_setinterval.asp) – RonyLoud

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(); 
    } 
    } 
} 
相關問題