这里是我的button
代码:在JavaScript中点击触发按钮?
<button class="popup-trigger" data-modal="modal-1"></button>
我怎么能触发按钮的点击,甚至与数据模式modal-1
触发类popup-trigger
?
想知道纯JavaScript,如果你不能这样做,那么jQuery。感谢
这里是我的button
代码:在JavaScript中点击触发按钮?
<button class="popup-trigger" data-modal="modal-1"></button>
我怎么能触发按钮的点击,甚至与数据模式modal-1
触发类popup-trigger
?
想知道纯JavaScript,如果你不能这样做,那么jQuery。感谢
找到你的DOM元素,然后调用点击方法:
document.getElementById("myButton").click();
可以有不同数量的第二使用jQuery
<button id="my-btn" class="popup-trigger" data-modal="modal-1"> </button>
<script>
$("#my-btn").click(function(){
//do something here
})
</script>
在纯JavaScript的方式
<button class="popup-trigger" onclick="myFunction()" data-modal="modal-1"> </button>
<script>
function myFunction(){
//do something here
}
</script>
:
// Since there can be multiple elements with the class "popup-trigger", it returns an array. Putting the [0] will call the first button with the class "popup-trigger".
var myButton = document.getElementsByClassName("popup-trigger")[0];
// If you wanted to check clicks on ALL buttons with the class, remove the [0] at the end.
// Check for clicks on the button
myButton.onclick = function(e) {
alert(e.target.getAttribute("data-modal"));
}
<button class="popup-trigger" data-modal="modal-1">Button</button>
我插入注释解释它。如果您有任何问题,请告诉我。
这个怎么样?
let button = document.querySelectorAll('button.popup-trigger')
function myFunction(){
alert("Button pressed")
}
button.forEach(function(element){
if (element.dataset.modal == "modal-1"){
\t \t \t element.addEventListener("click", myFunction, false);
}
})
<button class="popup-trigger" data-modal="modal-1">Button 1</button>
<button class="popup-trigger" data-modal="modal-2">Button 2</button>
<button class="popup-trigger" data-modal="modal-3">Button 3</button>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click – Mahi