我有一个站点范围的JS,它为各种事件创建监听器,但在某些情况下我需要调用特定的函数,如下面的代码所示,我需要调用函数call,但它的没有被叫到。
<html>
<head>
<script>
window.onload = function ()
{
var inputs = document.getElementsByTagName("input");
var len = inputs.length;
for (var i=0; i < len; i++)
{
if (inputs[i].getAttribute("type") == "text")
{
var element = inputs[i];
element.onfocus = function()
{
var id = element.getAttribute("id");
alert(id);
}
}
}
}
function call(element)
{
element.value="";
}
</script>
</head>
<body>
<input type="text" name="myvar1" value="same content" id="noviceid" onfocus="call(this);">
<input type="text" name="myvar2" value="same content" id="noviceid" onfocus="call(this);">
</body>
</html>
请提出建议。我想将两者都称为onfocus。我是 JavaScript 新手。
最佳答案
因此,一旦页面加载(使用正确的 call
onfocus
处理程序),您就可以运行 window.onload
来覆盖所有这些处理程序。我想这不是你想要做的。相反,如果可能的话,您可以使用 DOM2 事件:
element.addEventListener("focus", function(event)
{
var id = event.target.getAttribute("id");
alert(id);
}, false);
关于javascript - 绑定(bind)多个事件时调用特定函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10398762/