触发按钮点击javascript?

时间:2016-11-23 19:28:25

标签: javascript jquery html

这是我的button代码:

<button class="popup-trigger" data-modal="modal-1"></button>

如何使用数据模式popup-trigger触发按钮点击甚至触发课程modal-1

想在纯javascript中知道,如果你不能这样做,那么jquery。感谢

4 个答案:

答案 0 :(得分:6)

找到你的DOM元素,然后调用click方法:

document.getElementById("myButton").click(); 

答案 1 :(得分:1)

可以有多种方式

<button class="popup-trigger" onclick="myFunction()" data-modal="modal-1"> </button>
<script>
function myFunction(){
 //do something here
}
</script>

其次使用jQuery

<button id="my-btn" class="popup-trigger" data-modal="modal-1"> </button>
<script>
$("#my-btn").click(function(){
 //do something here
 })
</script>

答案 2 :(得分:0)

纯JavaScript:

// 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>

我插入了解释它的评论。如果您有任何问题,请告诉我。

答案 3 :(得分:0)

这个怎么样......

&#13;
&#13;
let button = document.querySelectorAll('button.popup-trigger')

function myFunction(){
    alert("Button pressed")
}

button.forEach(function(element){
    if (element.dataset.modal == "modal-1"){
			element.addEventListener("click", myFunction, false);
    }
})
&#13;
<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>
&#13;
&#13;
&#13;