[英]Simulate User Click Event with JavaScript on Bootstrap Button
如何使用Javascript模擬Bootstrap按鈕的click事件以執行綁定到Button的默認操作?
我需要此來自動測試網站。
Bootstrap本身不會在Button上添加任何事件,事件會冒泡到body元素上,然后工作就完成了。
$(“ btn.btn-outline-danger”)。click()不起作用$(“ btn.btn-outline-danger”)。trigger(“ click”)不起作用
試試這個。
$(document).on('click', '.btn',function(){
alert('click');
});
由於Bootstrap使用jQuery作為依賴項,因此您可以用jQuery方式模擬click事件。
$('.btn').click(function(){
console.log('Event Triggered');
});
不包括jQuery,Vanillajs。
var button = document.getElementByClassName('.btn');
button.onclick = console.log('Event Triggered');
事件應冒泡到父級(除非明確阻止)。 考慮以下簡單的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中應該相同。
香草js版本:
document.querySelector(".parent").addEventListener("click", function(){alert("hello")});
document.querySelector(".child").click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.