2017-10-17 115 views
2

我想在html文檔中添加谷歌趨勢圖。問題是我必須抓住點擊關鍵字並將其傳遞到谷歌趨勢功能,因此它可以返回數據作爲點擊關鍵字。但由於某種原因,當我打電話谷歌趨勢功能(named-TIMESERIES)內.click範圍它只加載圖表不是整個HTML,所以我必須從外部調用此功能.click範圍。原因是計時問題。請看看這種時機的解決方案issue solution here我不能用我的代碼實現這個解決方案。如果你能,那麼它真的幫助我。在此先感謝使用.click()全局變量範圍內的javascript時間問題

<script> 
    function TIMESERIES(categoryName) { 
    return trends.embed.renderExploreWidget("TIMESERIES", { 
     "comparisonItem": [{ 
     "keyword": categoryName, 
     "geo": "", 
     "time": "today 12-m" 
     }], 
     "category": 0, 
     "property": "" 
    }, { 
     "exploreQuery": "q=arts&date=today 12-m", 
     "guestPath": "https://trends.google.co.in:443/trends/embed/" 
    }); 
    } 

    var categoryName = ""; 

    $(".SearchMainCategory, .SearchSubCategory").click(function() { 
    categoryName = $(this).find("#Level1CatsName").val(); 
    if (typeof categoryName === "undefined") { 
     categoryName = $(this).find("#Level2CatsName").val(); 
    } 

    // TIMESERIES(categoryName) if i call this function from where then only this function (google trend chart actually) loads and page other contents not loading. so i need to call from outside then it works fine but i cant access "categoryName" variable from ourside. 
    }); 

    TIMESERIES(categoryName); 
</script> 

回答

0

隨着寫入,你會立即調用你的函數這樣的代碼:`時間序列(類別名稱=「「),因爲類別名稱沒有價值,而這個功能是直接調用文檔時加載。

將您的TIMESERIES函數放置在點擊處理程序中是正確的。你可能認爲是包裝整個腳本在這種包裝的:

(function() { 
    // This only gets called after the HTML is loaded. 
    // Also be sure that you insert your scripr below its targeted elements. 
    // Then put your code here. 
}) 

而且 - 你應該有#level1CatsName#level2CatsName只有一個實例。因此,您可以縮短這些線路從

categoryName = $(this).find("#Level1CatsName").val();

categoryName = $("#Level1CatsName").val()

按照該意見要求,您只需將代碼放到一個包裝(函數(){})。認識到您的標籤被插入以下的目標元素仍然很重要。

(function() { 
     function TIMESERIES(categoryName) { 
     return trends.embed.renderExploreWidget("TIMESERIES", { 
      "comparisonItem": [{ 
      "keyword": categoryName, 
      "geo": "", 
      "time": "today 12-m" 
      }], 
      "category": 0, 
      "property": "" 
     }, { 
      "exploreQuery": "q=arts&date=today 12-m", 
      "guestPath": "https://trends.google.co.in:443/trends/embed/" 
     }); 
     } 

     var categoryName = ""; 

     $(".SearchMainCategory, .SearchSubCategory").click(function() { 
     categoryName = $("#Level1CatsName").val(); 
     if (typeof categoryName === "undefined") { 
      categoryName = $("#Level2CatsName").val(); 
     } 

     TIMESERIES(categoryName); 
     }); 
}) 
+0

你能用我現有的代碼來實現它嗎? –

+0

@JohnLk已更新。 – Naltroc