2013-01-14 86 views
0

我目前正在使用google cse,並且我想知道它是否可以跳轉到特定的搜索詞。例如,如果我在我的頁面上看到出版物這個詞,並且頁面上有一部分出版物,是否可以通過使用實施的Google搜索直接跳到本部分?Google CSE - 跳轉到特定關鍵字

此刻每次搜索我都會將我引導到放置關鍵字的網頁的開頭。

問候馬丁

回答

0

這是可能的,是的,但你必須做一些編碼。如果您考慮Google搜索的工作方式,它會生成一個鏈接列表。它無法控制一旦你到達其他頁面會發生什麼。所以,你想在目標頁面上發生的任何事情,你都必須自己編碼。如果你真的想這樣做,你可以這樣設置:

首先,你會想使用V1 CSE,因爲它提供了在搜索完成時設置回調函數的能力,簡化的V2不會。見V1文件位置:https://developers.google.com/custom-search/docs/js/cselement-devguide

下面是從該網頁的示例代碼,修改,添加一個回調函數:

<!-- 
    copyright (c) 2012 Google inc. 

    You are free to copy and use this sample. 
--> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title>Google Custom Search Element API Example</title> 
    <script src="https://www.google.com/jsapi"></script> 
    <script type="text/javascript"> 
     google.load('search', '1'); 
     google.setOnLoadCallback(function(){ 
      customSearchControl = new google.search.CustomSearchControl().draw('cse'); 
     }, true); 
      customSearchControl.setSearchCompleteCallback(this, searchCompleteFn); 
    </script> 
    </head> 
    <body style="font-family: Arial;border: 0 none;"> 
    <div id="cse" style="width:100%;">Loading...</div> 
    </body> 
</html> 

然後你就可以創建一個回調函數,像這樣:

function searchCompleteFn(control, searcher) { 
    //your code 
} 

在你的代碼,你會想要獲得cse div中的所有a.gs-title元素,並修改它們的href屬性來添加用戶的查詢。這樣,你的目的地頁面就可以看到用戶搜索的內容並採取適當的行動(滾動到適當的部分,突出顯示關鍵字,無論你想要什麼)。例如,如果現有的href是http://www.yoursite.com/somepath/somepage.html,則可以將其更改爲http://www.yoursite.com/somepath/somepage.html#query=[user_query]。

[USER_QUERY]由control.getInputQuery給出()

最後,在你的目的地的網頁你會JavaScript的檢查中的location.hash查詢參數,並採取適當的行動。

我猜這是比你感興趣的方式更多的工作,但也許這對某人會有幫助。