javascript - 绑定(bind)多个事件时调用特定函数

标签 javascript

我有一个站点范围的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/

相关文章:

javascript - Angular 2 :RxJS Subject not responding to events

javascript - 限制 javascript 变量的最小/最大整数

php - 让 json 中的每个 "li"成为它自己的链接?

javascript - hapijs - 在插件完成注册之前无法启动服务器

php - 选择select中的所有选项

javascript - 如何使 jQuery POST 函数打开新页面?

javascript - 使用node.js中的AWS ec2.describeInstances从嵌套对象中提取数据

javascript - jQuery 使用 keydown/keyup/keypress 事件在按住按键时仅触发一次而不是多次

javascript - <li></li> 中的数组值

javascript - 如何将 dockerfile 环境变量传递给node.js 文件?