我正在使用以下功能来完成我的任务。当光标离开文本框时它工作正常,但如果我想从代码中触发相同的事件,比如下一个函数,我会收到错误......
function addEvent( obj, type, fn ) {
if (obj.addEventListener) {
obj.addEventListener( type, fn, false );
}
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
obj.attachEvent( "on"+type, obj[type+fn] );
}
else {
obj["on"+type] = obj["e"+type+fn];
}
}
function addEventByName(ObjName, event, func){
MyEle = document.getElementsByName(ObjName);
addEvent(MyEle[0], event, func);
}
addEventByName("txtBox", 'blur', function(){
alert('hello');
});
function fire(){
x = document.getElementsByName('txtBox')[0];
x.blur(); //gives error
x.onblur(); //gives error
}
答案 0 :(得分:0)
在this answer中调整作为jQuery扩展名提供的代码,这是一个可用于以编程方式跨浏览器触发事件的函数:
function fireEvent(el, eventType)
{
if (document.createEvent)
{
var evt = document.createEvent("HTMLEvents");
evt.initEvent(eventType, false, false);
el.dispatchEvent(evt);
}
else if (document.createEventObject)
{
el.fireEvent("on" + eventType);
}
}
您的fire
功能将如下所示:
var x = document.getElementsByName("txtBox")[0];
fireEvent(x, "blur");