简体   繁体   English

如何模拟输入框上的单击事件

[英]How to simulate click event on an input box

I am trying to simulate click on an input box. 我正在尝试模拟输入框上的单击。 When its clicked manually, a drop down auto suggestion box appears as suggestions about past searches. 手动单击时,将出现一个下拉自动建议框,作为有关过去搜索的建议。 However, when I try to simulate the click programmatically, I'm getting the error that 'object doesn't support click method'. 但是,当我尝试以编程方式模拟点击时,出现了“对象不支持点击方法”的错误。 Is there any other way to do this? 还有其他方法吗? All I want is the click event and the auto suggestion box to drop down. 我只需要单击事件和下拉的自动建议框。 Btw, this is Gmail's Search Mail input box on their mailbox that I am trying to play around with through web console. 顺便说一句,这是我尝试通过Web控制台使用的Gmail邮箱中的Search Mail输入框。

I have tried to call click function through className, but it gives me the error of either undefined or object doesn't support click. 我试图通过className调用click函数,但是它给了我未定义或对象不支持click的错误。 This is the widget that I am talking about: 这是我正在谈论的小部件:

  <input name="q" class="gb_cf" aria-haspopup="true" aria-owns="gs_sbt50" aria-live="off"  dir="ltr" spellcheck="false" aria-label="Search mail" type="text" placeholder="Search mail" value="" autocomplete="off">

  <input disabled="" class="gb_cf" id="gs_taif50" dir="ltr" autocomplete="off">

Few things that I have tried: 我尝试过的几件事:

    document.getElementbyClassName("gb_cf")[0].click(); 
    document.getElementbyName("q")[0].click();
    document.getElementbyId("gs_taif50").click();

None of them work. 他们都不工作。 Any ideas? 有任何想法吗?

You need to .focus() instead of .click() 您需要.focus()而不是.focus() .click()

document.getElementbyClassName("gb_cf")[0].focus(); //or
document.getElementbyId("gs_taif50").focus();

If you want to use pure/native javascript , you can use the onfocus attribute of the input element to call a Js function. 如果要使用纯/本地javascript ,则可以使用input元素的onfocus属性来调用Js函数。

 <script> function showButton(){ document.getElementById('mybutt').style.display = "block"; } </script> <body> <input id="myinp" type="text" placeholder="place" onfocus="javascript:showButton()"/> <button id="mybutt" style="display:none;">OK</button> </body> 

In the above file, you should see the "OK" button appear when you click on the input field. 在上面的文件中,当您单击输入字段时,应该看到出现“确定”按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM