我的代码将onfocus事件分配给元素有什么问题?

use*_*660 3 javascript onfocus

我有一个以下代码,我试图将onfocus事件分配给元素,以便每当元素聚焦时,调用alert.但是,警报仅在加载页面时出现,并且从此之后才会出现.

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

<script type="text/javascript">
function loadings(){
    document.getElementById("foo").onfocus = alert("foo"); 
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

请注意,我无法做到<input type="text" id="foo" onfocus="alert('foo')"/>我想要实现的目标.

此外,这应该适用于Firefox,Chrome,IE,Safari.

提前致谢!

rsp*_*rsp 5

这段代码:

document.getElementById("foo").onfocus = alert("foo");
Run Code Online (Sandbox Code Playgroud)

将调用alert()的结果分配给onfocus属性.你的意思是:

document.getElementById("foo").onfocus = function(){ alert("foo"); };
Run Code Online (Sandbox Code Playgroud)

这是使用DOM Level 0事件模型,每个事件只能有一个处理程序.如果你想要更灵活的东西,同时仍然跨平台,那么你可以尝试一些库为你抽象事件模型,就像jQuery一样:

$('#foo').focus(function(){ alert("foo"); });
Run Code Online (Sandbox Code Playgroud)

这样你就不必担心IE中的attachEvent和其他所有的addEventListener,但是如果你只需要像你的例子那样简单的情况,那么Level 0模型就完全没问题,适用于所有浏览器.