开发者

What is wrong with my code for assigning onfocus event to the element?

I have a following code which I tried to assign onfocus event to the element, so that whenever the element gets focused, call alert. However, alert only appears when the page loaded, and never after that.

<html>
<head>
</head>
<body onload = "loadings();">
<div>   
    <form>  
        <input type="text" id="foo"/>
    </form>
</div>

<script typ开发者_如何学Pythone="text/javascript">
function loadings(){
    document.getElementById("foo").onfocus = alert("foo"); 
}
</script>
</body>
</html>

Please note that I can't do <input type="text" id="foo" onfocus="alert('foo')"/> for the thing I am trying to achieve.

Also this should work in Firefox, Chrome, IE, Safari.

Thanks in advance!


This code:

document.getElementById("foo").onfocus = alert("foo");

assigns the result of calling alert() to the onfocus property. What you meant is:

document.getElementById("foo").onfocus = function(){ alert("foo"); };

This is using the DOM Level 0 event model where you can only have one handler per event. If you want something more flexible while still cross-platform then you may try some library to abstract the event model for you like jQuery does:

$('#foo').focus(function(){ alert("foo"); });

That way you don't have to worry about attachEvent in IE vs. addEventListener in everything else, but if you only need the simple case like in your example then the Level 0 model is perfectly fine and works across all browsers.


rsp's answer is correct, and is in my opinion a better style. To better understand the solution compare this syntax with rsp's. Both achieve the same result.

function MyEventHandler ()
{
    alert("foo");
}

document.getElementById("foo").onfocus = MyEventHandler;

The key thing to remember with the syntax is you include the function name, but not the parentheses (). You want to refer to the function itself, not invoke it. The event will invoke the function when it is raised.


You could use the addeventlistener like below.

document.getElementById("foo").addEventListener("focus", function(){alert("foo")}, false);


Here's a generic function to add an event handler

function addEvent( obj, type, fn ){
    if(!obj){
        return;
    }
    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] );
        }
    }
}

then

addEvent(document.getElementById('foo'),'focus',myEventhandler);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜