开发者

What's wrong with addlistener... how do i fire my event

开发者 https://www.devze.com 2022-12-24 23:35 出处:网络
I am using the following functions to do my task. It works fine when cursor moves away from textbox but if i want to fire the same event from code say like next function i get error...

I am using the following functions to do my task. It works fine when cursor moves away from textbox but if i want to fire the same event from code say like next function i get error...

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.even开发者_运维技巧t ); }
  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
}


Adapting the code given as a jQuery extension in this answer, here's a function you can use to programmatically fire an event cross-browser:

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);
    }
}

Your fire function would then look like this:

var x = document.getElementsByName("txtBox")[0];
fireEvent(x, "blur");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号