如何使用 jQuery 或 JavaScript 模拟点击按钮的动作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5015054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:15:14  来源:igfitidea点击:

How to use simulate the action of clicking button with jQuery or JavaScript?

javascriptjquery

提问by Ricky

I need to use JavaScript to simulate the action of clicking buttons. How do I achieve it? Can I achieve it with jQuery?

我需要使用 JavaScript 来模拟点击按钮的动作。我如何实现它?我可以用 jQuery 实现它吗?

回答by gor

Yes, you can do it with jquery. Use triggerfunction. Here documentation. Here is sample:

是的,你可以用 jquery 做到这一点。使用trigger功能。这里的文档。这是示例:

$('#foo').trigger('click');

回答by jevakallio

You can execute the click event handler assigned to a button control:

您可以执行分配给按钮控件的单击事件处理程序:

$("#mybutton").click();

回答by Peter ?rneholm

Simply .click():

只需.click()

$("#theButton").click();

回答by Nisal Edu

Following code will print clicked two times one from $('.submitBtn').click();and other $('.submitBtn').trigger('click')

以下代码将打印点击两次来自$('.submitBtn').click();和其他$('.submitBtn').trigger('click')

$(document).ready(function() {

  $('.submitBtn').on('click', function() {

   console.log("Clicked!");

  })

$('.submitBtn').click();
$('.submitBtn').trigger('click')



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button menu="submitBtn" class="submitBtn len4 btn" title="submit" data-code-m="sbm.submit"> Click me
        </button>

回答by Chaudhary

Please try following code e.g.:

请尝试以下代码,例如:

setTimeout(function() {
    $(".class_name").trigger('click');  
}, 8000);

回答by Gary Carlyle Cook

Wrapping it in this 'anonymous document ready function' will make sure the button is there before you click it. Just in case it tries to click before the element you want to click is loaded. This would fix that issue.

将它包装在这个“匿名文档就绪功能”中将确保按钮在您单击之前就在那里。以防万一它在您要单击的元素加载之前尝试单击。这将解决该问题。

Also, remember that an ID uses a hash (i.e. #close-button) but if you want to click an element that has a CLASS then swap the hash for a single dot (i.e. .close-button).

另外,请记住 ID 使用散列(即 #close-button),但如果您想单击具有 CLASS 的元素,则将散列交换为单个点(即 .close-button)。

jQuery(document).ready(function() {
        $("#close-button").trigger('click');    
});