Javascript:“onchange”事件不适用于“值”改变“文本输入”宾语 [英] Javascript: "onchange" event does not work with "value" change in "text input" object
问题描述
我有一个javascript 输入
对象,其中 type =text
随附 onchange
由(相关行)创建的事件:
I have a javascript input
object with type="text"
coming along with an onchange
event which is created by (related lines):
var id_box = document.createElement('input');
id_box.id = 'id_box';
id_box.type = 'text';
id_box.onchange = function()
{
alert("Changed!");
}
更改此值
在我使用的输入
字段中:
For changing this value
in this input
field I use:
var a = document.createElement('a');
a.innerHTML = "A";
a.onclick = function()
{
document.getElementById('id_box').value = 'A';
}
onchange
事件仅通过键盘输入改变值,但不能通过上述功能改变值。有没有办法让这个有效?
The onchange
event works only changing value by keyboard typing but not for changing value by above function. Is there any way to make this works?
请看一下: http://jsfiddle.net/zCMdV/7/
推荐答案
你是什么浏览器?使用?
What browser are you using?
我做了这个例子,这对我有用......微妙的变化是我在将它附加到div元素之前将事件添加到输入。
I have made this example, which works for me... the subtle change is that I add the event to the input before I append it to the div element.
<div id="test"></div>
<script type="text/javascript">
var id_box = document.createElement('input');
id_box.type = 'text';
id_box.onchange = function()
{
alert("Changed!");
}
document.getElementById("test").appendChild(id_box);
</script>
在JS Fiddle上看到它: http://jsfiddle.net/Sohnee/zCMdV/
See it in action on JS Fiddle: http://jsfiddle.net/Sohnee/zCMdV/
更新:
如果您要自动更改值,您可以执行同样的操作来触发更改事件......
If you are going to automate the changing of the value, you can do the same to trigger the change event...
http://jsfiddle.net/Sohnee/zCMdV/10/
document.getElementById('id_box').onchange();
这篇关于Javascript:“onchange”事件不适用于“值”改变“文本输入”宾语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!