同一页面中的两个自定义搜索禁用搜索预测

Two custom searches in same page disables search predictions

在为较大的显示器和移动设备使用不同样式时,我被迫在同一页面插入两个google自定义搜索框。搜索仍然完美,但问题是在插入第二个搜索框后搜索预测不再可用

(function() {
    var cx = '*****************:**********';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

相同的代码在同一页面中使用了两次(尤其是 重复使用 id ),这导致了我认为的冲突。已经提到了类似的帖子“How to have multiple Google Custom Search field on the same page' and '”,但这些不是我所面临情况的解决方案。 如何使同一页面中的两个搜索框以相似的方式工作而不引起冲突?

我目前正在试验这个。在同一页面上使用不同的 cx 获得 2 个 cse 并不难,但无法使建议生效。 v2控件api方法描述不是很清楚。

但是对于单个 cx,您可以这样做:

html:

<div id="first"></div>
<br/>
<div id="second"></div>

js:

var renderSearchElement = function() {
    google.search.cse.element.render({
        div: "first",
        tag: 'search'
    });
    google.search.cse.element.render({
        div: "second",
        tag: 'search'
    });
};

var myCallback = function() {
    if (document.readyState == 'complete') {
        renderSearchElement();
    } else {
        google.setOnLoadCallback(renderSearchElement, true);
    }
};

window.__gcse = {
    parsetags: 'explicit',
    callback: myCallback
};

var loadElements = function() {
    var cx = '*****************:**********';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
}

loadElements();

演示: https://jsfiddle.net/501g48d4/

CSE v2 控制 API 和渲染参数:https://developers.google.com/custom-search/docs/element