在Bootstrap按钮上使用JavaScript模拟用户Click事件

时间:2019-07-14 14:21:50

标签: javascript twitter-bootstrap

我如何使用Javascript模拟Bootstrap按钮的click事件以执行绑定在Button上的默认操作?

我需要它来自动测试网站。

Bootstrap本身未在Button上添加任何事件,这些事件冒泡到body元素上,并且工作已完成。

$(“ btn.btn-outline-danger”)。click()无法正常工作 $(“ btn.btn-outline-danger”)。trigger(“ click”)无法正常工作

3 个答案:

答案 0 :(得分:1)

尝试一下。

$(document).on('click', '.btn',function(){
    alert('click');
});

答案 1 :(得分:0)

由于Bootstrap使用jQuery作为依赖项,因此您可以用jQuery方式模拟点击事件。

$('.btn').click(function(){
  console.log('Event Triggered');
});

不包括jQuery,Vanillajs。

var button = document.getElementByClassName('.btn');
button.onclick = console.log('Event Triggered');

答案 2 :(得分:0)

事件应冒泡到父级(除非明确阻止)。考虑以下简单的html结构:

<div class="parent">
    <div class="child"></div>
</div>

在下面的代码中,父级具有附加到click事件的功能。触发子级点击事件时,父级事件会响应。

$(".parent").click(function() {alert("hello")}); // attach event
$(".child").click(); // trigger event

https://jsfiddle.net/epqdz2a1/

在Bootstrap中应该相同。

Vanilla js版本:

document.querySelector(".parent").addEventListener("click", function(){alert("hello")});
document.querySelector(".child").click();
相关问题