javascript - 添加 onfocus 监听器而不是 onload

标签 javascript

我在js文件中有这样的脚本,我从jsp调用,我需要添加监听器而不是“onload”。 对我来说重要的是: 1)必须是纯js,没有jQuery什么的 2)输入标签将动态创建(也许这很重要) 3)必须是外部js文件(<script src="<c:url value="/js/focus.js" />"></script>),但不能是标签<script>function.....</script> jsp页面内

    onload = function () {
        var allInput = document.getElementsByTagName("input");
        for (i = 0; i < allInput.length; i++) {
        allInput[i].onfocus = showHint
    }
};

function showHint() {
    var hint = document.getElementById("hint");
    hint.innerHTML = this.name + " " + this.value;
    hint.style.display = "block";
};

最佳答案

页面在未加载之前可以获得焦点。如果页面未加载,则您的输入不存在,因此 window.onfocus 无法设置 allInput[i].onfocus。当页面刷新且焦点位于开发工具上时,页面有机会在 window.onfocus 调用之前创建输入。

window.onfocus 放入 window.onload 中,以便在页面加载后始终调用它。如果您不想覆盖 window.onload,请改用 addEventListener:

addEventListener('load', function () {
  addEventListener('focus', function() {
    var allInput = document.getElementsByTagName("input")
    for (i = 0; i < allInput.length; i++) {
      allInput[i].addEventListener('focus', showHint)
    }
  }
})

function showHint() {
  var hint = document.getElementById("hint")
  hint.innerHTML = this.name + " " + this.value
  hint.style.display = "block"
}

关于javascript - 添加 onfocus 监听器而不是 onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251021/

相关文章:

Javascript 代码片段在 Safari 11 和 12 中不起作用

javascript - 在同一函数中调用 `Function` 与 `Function()`

javascript - 如何使用 Angular 模块 'ui-route' 在指令中查找 templateUrl 并且不会在 MVC .NET 上出现错误

php - 如何从 PHP 将正确的数据类型传递给 Javascript

javascript - 在 Sharepoint 2013 中使用 JavaScript 检索查找的链接列表

javascript - 如何通过动态构建多维数组进行搜索/过滤/类型匹配

javascript - 如何在 x 轴上仅显示 ForceShow-ticks?

javascript - 使用javascript在testcafe中跨测试调用元素

javascript - 文件读取器 API : viewing the contents outside of a callback

Javascript - 创建自己的书签网站并提示?