我正在尝试在同一页面上实现两个(不同的)Google CSE 搜索框。问题是只有第一个实例才能正常工作。例如,标题中的站点范围搜索框,然后在某些页面上,在站点的狭窄孤岛内搜索的第二个搜索框等。

这不能正常工作,因为为每个框使用谷歌生成的代码,它们都获得相同的表单 ID,这显然是无效的。这会导致 google 水印品牌无法出现在框 #2 中,并且一些自动/谷歌生成的变量也无法为第二个框生成,例如 ss 参数(搜索 session )。

现在,搜索本身在两个框中都有效,例如用户搜索,被带到正确的结果页面,并显示正确的结果。

我只是想解决这个问题:我怎样才能使第二个表单获得不同的 ID 值(并且仍然正常工作 - 因为谷歌的 javascript 查找 ID cse-search-box )我尝试向 ID 和 NAME 属性添加唯一标识符<form> 元素,但这导致 google.com javascript 出现故障(因为我相信它只查找“cse-search-box”)

代码如下:

搜索框 1:

<form id="cse-search-box" name="cse-search-box" class="search searchHeader" method="get" action="/search">
<input type="hidden" name="cx" value="partner-pub-0000000000000000:000" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" id="q" class="text_input" />
<input type="submit" name="sa" value="Search" class="submit" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>

搜索框 2:
<form id="cse-search-box" name="cse-search-box" class="search searchWebDirectory" method="get" action="/search">
    <input type="hidden" name="cx" value="partner-pub-0000000000000000:111" />
    <input type="hidden" name="cof" value="FORID:10" />
    <input type="hidden" name="ie" value="UTF-8" />
    <input type="text" name="q" id="q" class="text_input" />
    <input type="submit" name="sa" value="Search" class="submit" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>

最佳答案

发件人:http://www.google.com/cse/docs/cref.html

/coop/cse/brand 中名为“form”的参数输出代码中的第一个 getElementById。因此,使用 http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en 将创建一个 cse-search-box 目标代码,而给它 box2 将在不同的 ID 上触发。保留关键字 searchbox_demo

如果您愿意,可以试一试: http://jsfiddle.net/JTV6f/1/ 。但是,考虑到您在做什么,如果我是您,我会切换到 V1 或 V2 API。

关于javascript - 同一页面上的多个 Google CSE(自定义搜索引擎)框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15589725/

10-12 00:04
查看更多