這不是很優雅,但我最終解決了這個問題,方法是設置一組搜索條件,然後用自定義搜索按鈕填充Google自定義搜索字段。
使用this SO post作爲模型,除了自定義搜索HTML之外,還使用新按鈕設置了我的HTML。
<form id="cse-search-box" action="http://google.com/cse">
<input type="hidden" name="cx" value="partner-pub-2789521296837340:9402765321" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="31" />
<input type="submit" name="sa" value="Search" />
<!-- This is the new button - the "random" ID allows it to be targeted separately. -->
<input id="random" type="submit" name="random" value="Random" />
</form>
現在的形式成立,我們需要添加的可能的搜索項的數組以及函數隨機選擇從陣列中的一個話題。
// With input selected, do this on click
$("input#random").on('click', function() {
// The array of possible search terms.
var myArray = ['animals','dogs','cats', 'emu','fish','snakes', 'panda bears','meerkats','spiders','birds'];
// Choose a term randomly
var rand = myArray[Math.floor(Math.random() * myArray.length)];
// Write them term in the search box and then submit the search
var input = $("input[name='q']");
input.val(input.val() + ' ' + rand);
$("form#cse-search-box").submit();
});
顯然,數組越大,隨機性越好。我想改善的一件事是通過閱讀這些正在搜索的博客和網站的RSS提要以編程方式創建數組。儘管如此,現在仍然有效。
因爲我學習,我沒有看到一個重大的在您的實施和我在下面發佈的不同之處。是否更好 - 一般來說 - 使用API方法來運行搜索?換句話說,爲什麼這個答案比我提出的解決方案更好? – Brian 2015-03-31 13:24:28
因爲這是Google推薦的方式,因爲它不會改變您的實際位置,因爲如果有一天,Google決定改變它處理這些請求的方式(例如,如果它們阻止直接訪問您要轉移的頁面你的用戶),你將不得不重新編寫你的代碼。也就是說,選擇哪種解決方案最適合您的需求取決於您。 – Kaiido 2015-03-31 15:18:35