在javascript中调用自定义Google搜索标记时出现问题

时间:2016-05-05 09:27:45

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

我正在使用谷歌自定义搜索API,但我不想谷歌搜索默认文本框,所以对于同样的共鸣我已经创建了一个新的文本框和一个按钮。点击我的自定义按钮后,我从自定义文本框中获取搜索键值并输入谷歌搜索默认文本框。但在我的javascript函数中,我无法执行谷歌搜索提交按钮的点击事件。我现在知道谷歌搜索提交按钮的类名,我怎样才能在我的java脚本函数中执行click事件?

谷歌搜索dubmit按钮类名是“gsc-search-button gsc-search-button-v2”

现在,在以下方法中,我需要执行上述类的click事件。

<script>
function myFunction() {
   document.getElementById('gsc-i-id1').value = document.getElementById('customTextBox').value;
 // here I need to perform click event for "gsc-search-button gsc-search-button-v2" class
}
</script>script>

我在以下链接中有演示示例

http://jsfiddle.net/3L4fd63g/3/

请提出任何建议

1 个答案:

答案 0 :(得分:2)

我看到了标签,因此有一个选项可以处理表单提交,因此文本框上的回车键也会执行搜索。

另外,要执行点击,您只需拨打.click()

即可

// Make sure in jsFiddle you have selected option onLoad.
(function() {
  var cx = '017643444788069204610:4gvhea_mvga'; // Insert your own Custom Search Engine ID here
  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);
})();

$(function(){

  $('#search').submit(function(e){
    $('.gsc-input').val($('#customTextBox').val());
    $('input.gsc-search-button').click();
    e.preventDefault();
  });

});
.search-box{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="search">
  <input type="text" id="customTextBox"/>
  <input type="submit" value="Click me" />
</form>

<div class="search-box">
    <gcse:searchbox></gcse:searchbox>
</div>

<gcse:searchresults></gcse:searchresults>