[英]Implementing an onclick event without JQuery
I have a bit of JQuery in my app that adds a click event to a class. 我的应用程序中有一些JQuery,它将click事件添加到类中。 The click event just removes a class on the parent element.
click事件只会删除父元素上的类。
$(function(){
$(".flash .close").on("click", function(){
$(this).parent().removeClass("active");
})
});
This is the only use of JQuery in my entire application, so I'd love to re-write this snippet without JQuery so I can eliminate that as a dependency all together. 这是JQuery在整个应用程序中的唯一用法,因此我很想在没有JQuery的情况下重新编写此代码段,因此可以将其作为依赖项一起消除。
However, I'm not sure where to begin in terms of implementing this click even in native javascript. 但是,即使在本机javascript中,我也不确定在实现此点击方面应该从哪里开始。 I don't know much about JavaScript and the little that I do know involves frameworks like JQuery and React.
我对JavaScript不太了解,而我所了解的很少涉及JQuery和React之类的框架。
Thanks! 谢谢!
Try with querySelectorAll
for select the element.Then classList.remove()
use for remove the class name of the parentElement
. 尝试使用
querySelectorAll
选择元素。 classList.remove()
用于删除parentElement
的类名称。
window.onload=function(){ document.querySelectorAll(".flash , .close").forEach(function(a){ a.addEventListener("click", function(){ this.parentElement.classList.remove("active"); }) }) }
.active{ color:red; }
<div class="active"> <a class="flash">hi</a> </div>
您可以从下面的参考资料中获取学习角度的参考:https://www.w3schools.com/js/js_htmldom_eventlistener.asp
Try this fiddle https://jsfiddle.net/z6uopyhy/1/ 试试这个小提琴https://jsfiddle.net/z6uopyhy/1/
var flashCloseButton = document.getElementsByClassName('close');
for(var i = 0; i < flashCloseButton.length; i++){
flashCloseButton[i].addEventListener("click", function(e) {
this.parentElement.classList.remove("active");
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.