我在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/