Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何手动触发onchange事件? [重复](How can I trigger an onchange event manually? [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

How to trigger event in JavaScript?(如何在JavaScript中触发事件?) 17 answers(17个答案)

I'm setting a date-time textfield value via a calendar widget.(我正在通过日历窗口小部件设置日期时间文本字段值。)

Obviously, the calendar widget does something like this :(显然,日历小部件会执行以下操作:) document.getElementById('datetimetext').value = date_value; What I want is : On changing value in the date-time textfield I need to reset some other fields in the page.(我想要的是:在更改日期时间文本字段中的值时,我需要重置页面中的其他一些字段。) I've added a onchange event listener to the datetimetext field which is not getting triggered, because I guess onchange gets triggered only when the element gets focus & its value is changed on losing focus.(我已经将一个onchange事件侦听器添加到了不会被触发的datetimetext字段中,因为我猜onchange仅在元素获得焦点并且其值更改为失去焦点时才被触发。) Hence I'm looking for a way to manually trigger this onchange event (which I guess should take care of checking the value difference in the text field).(因此,我正在寻找一种手动触发此onchange事件的方法(我认为应该注意检查文本字段中的值差异)。) Any ideas ?(有任何想法吗 ?)   ask by CodeTweetie translate from so

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

1 Reply

0 votes
by (71.8m points)

There's a couple of ways you can do this.(有两种方法可以做到这一点。)

If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:(如果onchange侦听器是通过element.onchange属性设置的函数,并且您不必担心事件对象或冒泡/传播,那么最简单的方法是只调用该函数:) element.onchange(); If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener / attachEvent , you need to do a bit of feature detection to correctly fire the event:(如果您需要它来完全模拟真实事件,或者通过html属性或addEventListener / attachEvent设置事件,则需要做一些功能检测以正确触发事件:) if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); element.dispatchEvent(evt); } else element.fireEvent("onchange");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...