Javascript 使用JS如何只调用一次click函数,相当于一个jQuery
喂,有人能帮我吗?我无法将这部分代码转换为JS:Javascript 使用JS如何只调用一次click函数,相当于一个jQuery,javascript,jquery,Javascript,Jquery,喂,有人能帮我吗?我无法将这部分代码转换为JS: $(".custom-select-trigger").on("click", function() { $('html').one('click',function() { $(".custom-select").removeClass("opened"); }); $(this).parents(".custom-select&quo
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
到目前为止,我已经做到了:
const customSelectTrigger = document.querySelector(".custom-select-trigger");
const customSelect = document.querySelector(".custom-select");
function showOptions(e) {
e.preventDefault();
customSelect.classList.toggle("opened");
e.stopPropagation();
}
但我无法为javascript完成这一部分:
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
下面是当您按下DOM中的任意位置时,从自定义选择中删除类
打开的
的工作代码
您需要使用JS并单击函数来执行此操作
要从元素中删除类,我们可以使用函数并通过查询选择器
获取元素的类列表
,该选择器将。自定义选择
编辑:如果只想在每次加载DOM时使用click函数一次。然后设置args{one:true}
将只调用函数一次
我重新创建了您的示例及其工作原理
运行下面的代码段
//获取HTML元素
const htmlElement=document.querySelector(“html”);
//获取要从中删除类的元素
const customSelect=document.querySelector(“.customSelect”);
//添加eventlistener以从类列表中删除打开的类
HtmleElement.addEventListener(“单击”,函数(e){
customSelect.classList.remove(“打开”);
console.log('类已删除')
e、 预防默认值();
},{once:true})代码>
。已打开{
背景色:红色;
}
单击DOM上的任意位置以从自定义选择中删除类
我的自定义选择
它不处理question@Ben答案更新为只调用函数一次。@始终搁置这个问题,兄弟,你能帮我吗addEventListener
有一个once
选项;