简体   繁体   English

jQuery触发点击事件

[英]jQuery trigger click event

I have a page with a search button on it. 我有一个带有搜索按钮的页面。

in my Javascript i have a click event that looks like this: 在我的Javascript中,我有一个如下所示的click事件:

if(blah){
  $('#search').click();
}

$('#search').on('click', function(){
  // Do something
});

What would be the reason the if statement wouldn't click the button to cause the onclick to fire? 如果if语句不单击按钮导致触发onclick原因是什么?

All of this is wrapped in an onReady as well. 所有这些也都包装在一个onReady中。

The html on the page is a standard button: 页面上的html是标准按钮:

<button id='search' type="button" class="btn btn-primary">Search RefID</button>

You seem to bind the handler after you triggered the click. 触发点击后,似乎绑定了处理程序。 The handler is not executed because it does not exist (at that moment). 该处理程序未执行,因为它当时不存在。

Put the if-clause after the click-handler and it works: 将if子句放在点击处理程序之后,即可生效:

http://jsfiddle.net/kksgj4xL/ http://jsfiddle.net/kksgj4xL/

var blah = true;

$('#search').click(function(){
  alert("poep");
});

if(blah){
  $('#search').click();
}

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

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