在自定义搜索引擎上的搜索框中添加搜索按钮

时间:2018-06-23 14:26:48

标签: javascript jquery html search google-search-api

如何向HTML添加搜索按钮?我尝试添加它,但是当我搜索显示结果的示例YouTube但不显示搜索文本YouTube时,如何解决此问题,我需要在此代码中进行哪些更改?谢谢

.main{
	position: absolute;
	top: 10px;
    left: 25%;
	width: 50%;
	height: auto;	
	text-align: center;
}
.q{
	padding: 5px;
	width: 90%;
	margin-top: -30px;
	border: solid 1px #c68e00;
	font-size: 17px;
	font-family: Arial;
	height: 40px;
}
<script>
    (function() {
        var cx = '004533415228465222070:r2ak9s12hwi';
        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:searchresults-only></gcse:searchresults-only>
</div>

<div class="main">
	<br/><br/>
	<form action="" method="GET">
 <input class="q" name="q" placeholder="Search by Name or type URL" title="Search ..." value="" /> 
</form>

1 个答案:

答案 0 :(得分:0)

我不确定结果如何,但希望这项工作能够成功。

在搜索输入中添加了id="searchbox"。和这两行。

var urlParams = new URLSearchParams(window.location.search);
document.getElementById('searchbox').value = urlParams.get('q');

您现在的完整代码如下所示。

<div class="main">
    <br/><br/>
    <form action="" method="GET">
 <input class="q" name="q" id="searchbox" placeholder="Search by Name or type URL" title="Search ..." value="" /> 
</form>
</div>
<script>
    (function() {
        var cx = '004533415228465222070:r2ak9s12hwi';
        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);
    })();
var urlParams = new URLSearchParams(window.location.search);
document.getElementById('searchbox').value = urlParams.get('q');
</script>
<gcse:searchresults-only></gcse:searchresults-only>
相关问题