在没有JQuery和onFocus()事件的情况下在Focus上触发Javascript事件
我想对html中的某些类触发java脚本事件。我不想使用任何jQuery或其他js事件,如在没有JQuery和onFocus()事件的情况下在Focus上触发Javascript事件,javascript,html,dom-events,Javascript,Html,Dom Events,我想对html中的某些类触发java脚本事件。我不想使用任何jQuery或其他js事件,如onfocus()。我不想在html代码中添加任何事件侦听器。但是js中的事件处理程序可能会被接受 我希望,这个例子可以帮助你 const txtName=document.getElementById('txt-name'); txtName.addEventListener('focus',e=>{ 警惕(‘嗨,我集中注意力了’) }) 要使用类获取所有元素,请执行以下操作: elements =
onfocus()
。我不想在html代码中添加任何事件侦听器。但是js中的事件处理程序可能会被接受 我希望,这个例子可以帮助你
const txtName=document.getElementById('txt-name');
txtName.addEventListener('focus',e=>{
警惕(‘嗨,我集中注意力了’)
})
要使用类获取所有元素,请执行以下操作:
elements = document.querySelectorAll('.class');
elements.forEach(element => element.addEventListener('focus', () => {handlerFunction});
你需要
element.addEventListener(“focus”,function(){})
,它与onfocus非常相似。我不想使用id的类。我想选择类似jquery类选择器的类,但不需要jqueryelements=document.querySelectorAll('.class');elements.forEach(element=>element.addEventListener('focus',()=>{handlerFunction});我编辑了我的答案,包括如何通过类获取所有元素并向它们添加事件侦听器。
elements = document.querySelectorAll('.class');
elements.forEach(element => element.addEventListener('focus', () => {handlerFunction});