2017-10-17 63 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