Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

用js操作dom(非用户操作)不触发onchange事件

//body
<button>全选</button>
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
 
//js
const btn=document.querySelector('button');
const input=document.querySelectorAll('input');

//添加点击事件,改变选择框的状态
btn.onclick=()=>input.forEach(e=>e.checked=!e.checked) 
//添加change事件,如果改变了输出1
input.forEach(e=>e.onchange=()=>console.log(1))

我直接点击选择框会输出1,但是点击按钮虽然选择框的状态会改变,但是没有输出1,没有触发onchange事件?这是什么原因啊?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

就是这么设计的。我也不是很清楚原因,猜测是为了防止事件死循环吧。如果需要事件的话,手动触发 click 事件吧。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...