2016-02-01 25 views
3

我已經添加谷歌自定義搜索引擎使用以下代碼。在我的html網站的谷歌自定義搜索引擎中的文本框中添加佔位符

(function() { 
    var cx = '005899633628958982661:wekn1lpckzg'; 
    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); 
})(); 

現在我對我的網站有一個工作搜索框,唯一的問題是我無法爲搜索文本框使用佔位符。

我也試過代碼

$('input.gsc-input').attr('placeholder', 'custom text here'); 

,但它無法正常工作。

+0

那是輸入是否正確?我也會用引號''' –

+1

你用document.ready調用這行嗎?我在 – progrAmmar

+0

以上的代碼中看不到它是的,它是很小的document.ready ..我也試過把代碼放在最後的頁面,但這也無濟於事。 – atul

回答

4

我用下面的代碼,它爲我工作!

(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); 
})(); 

window.onload = function(){ 
document.getElementById('gsc-i-id1').placeholder = 'SEARCH'; 
}; 

+0

我猜,document.getElementsByNames('search')[ 0] .placeholder更好..因爲搜索框的id是隨機的 –

+0

如果你使用的是GCS,那麼id可以通過inspect來確定,因爲在複雜的頁面上可能會有另一個與'search'同名的元素! AnuBhuvanendranNair document.getElementsByNames總是沒有效率和可靠的方式。 –

+0

谷歌自定義搜索生成id'gsc-i-id1',有時'gsc-i-id2'.. id值是我理解的隨機數。那麼document.getElementById如何可靠? –

0

這一次爲我的作品:

window.onload = demo; 

function demo() { 
    document.getElementById("gsc-i-id1").setAttribute("placeholder", "SEARCH") 
} 
相關問題