Javascript—以编程方式触发任何浏览器复选框的onChange事件

Javascript—以编程方式触发任何浏览器复选框的onChange事件,javascript,events,firefox,checkbox,onchange,Javascript,Events,Firefox,Checkbox,Onchange,我在HTML中有一些复选框,设置如下: <td nowrap width='25%'><label><input type='checkbox' name='chk[]' checked onChange="updateWindow('Label 1', this.checked)">&nbsp;Label 1</label></td> 首先的问题是,像这样勾选/取消勾选复选框不会触发onChange事件和相关方法。所以我手动

我在HTML中有一些复选框,设置如下:

<td nowrap width='25%'><label><input type='checkbox' name='chk[]' checked onChange="updateWindow('Label 1', this.checked)">&nbsp;Label 1</label></td>
首先的问题是,像这样勾选/取消勾选复选框不会触发
onChange
事件和相关方法。所以我手动触发它调用:

function activateEvent(item, actionShortName) {

    if (document.createEventObject){    // dispatch for IE
        item.fireEvent("on" + actionShortName); 
    }
    else {  // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(actionShortName, true, true); // event type,bubbling,cancelable
        item.dispatchEvent(evt);
    }
}
这在IE8和一些旧版本的Firefox上运行良好。 但是在Firefox23上,我有一个javascript错误告诉我:

"TypeError: item.dispatchEvent is not a function"

如何才能使此功能适用于所有浏览器?

您的
for
循环是错误的。
复选框
将是一个节点列表,并且您不能对该列表进行
for(in)
操作(除非您对属性名称感兴趣)


使用常规的
for(var i=0;i
循环。

你检查过这篇文章吗@宙斯盾:是的,这产生了完全相同的问题。为什么是++i而不是i++?没有理由。在这种情况下,这些是可互换的。这只是因为我习惯于这样写,从编写C++的运行时间中吸取了代码< i++>代码>。在代码< > item之前,添加<代码>控制台。日志(项)<代码>。这解决了我的问题。
function activateEvent(item, actionShortName) {

    if (document.createEventObject){    // dispatch for IE
        item.fireEvent("on" + actionShortName); 
    }
    else {  // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(actionShortName, true, true); // event type,bubbling,cancelable
        item.dispatchEvent(evt);
    }
}
"TypeError: item.dispatchEvent is not a function"