我正在尝试在html文档上添加Google趋势图表。问题是我必须抓住点击关键字并将其传递给谷歌趋势功能,以便它可以将数据作为点击的关键字返回。但出于某种原因,当我在.click范围内调用谷歌趋势功能(名为TIMESERIES)时,它只加载图表而不是整个html所以我必须从外部.click范围调用此函数。原因是时间问题。请看看这种时间的解决方案issue solution here我无法用我的代码实现此解决方案。如果你能,那真的帮助我。提前致谢
<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 :(得分:0)
使用按原样编写的代码,您将立即调用您的函数:`TIMESERIES(categoryName =&#34;&#34;)因为categoryName没有值,并且在加载文档时立即调用此函数。
将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() {
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);
});
})