Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - How to have multiple Google Custom Search field on the same page

I'm trying to have multiple search field on the same page with Google Custom Search (GCS) like this :

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

<gcse:search></gcse:search>

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

<gcse:search></gcse:search>

Unfortunatly, It does not work. The search is made with the same cx for every field. When It do the ajax request on this address : https://www.googleapis.com/customsearch/v1element... there is this value : &cx=user_id:field_id1 and the value is the same for both fields.

What is the solution?

I already seen this question : Multiple Google CSE (Custom Search Engine) Boxes on Same Page, but it seems to be on another version.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a tested solution. Took me a while but I'm slow and I don't use CSS all the time.

Use the V1 code. When you select Get Code on the setup screen there is an option for the V1 code.

Put your search code in a div

div tag

searchcode

end div tag

Make your cse variables unique. That will be two places at the top of the code.

div id='cse'

and a little lower

customSearchControl.draw('cse', options);

For each search these should be the same but different than the other searches. I used cse0, cse1, cse2.

This will fix the searches so each search will work as specified but they will still share the same CSS.

So scope your styles with the scoped attribute.

style type='text/css' scoped

Do this for each search code. Now your searches can have their own look and feel, color, etc.

http://deltaboogie.com/search

Thanks, Hairy Larry


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...