【发布时间】:2022-01-07 06:02:05
【问题描述】:
您好,请找到以下代码并帮助解决问题
<html>
<body>
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<script>
function fnAlertTitle(){
var strTitleFlag =document.test.fname.value.trim();
console.log("strTitleFlag::"+strTitleFlag);
if (strTitleFlag == "") {
alert("Please Select Fname");
document.test.fname.focus();
window.event.returnValue =false;
return;
}
}
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
</script>
<h1>The input element</h1>
<form name="test" action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" tabindex="1"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" tabindex="2" onFocus="javascript:fnAlertTitle();"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
按选项卡 ONFOCUS 事件调用一次,但同时按多次输入其调用,请帮助解决问题
【问题讨论】:
-
使用
console.log而不是alert。打开一个弹出窗口会自动切换焦点(因此最终会再次触发自身) - 您也可以在fnAlertTitle()中手动切换它以及。 -
Hi function fnAlertTitle() 调用 3 次
-
是的,使用
console.log而不是alert()进行测试(F12打开控制台);并关闭您的onFocus=..和fname.focus()。它们都是一个坏主意,将它们与alert结合起来更糟。专注不是你玩弄的东西。如果您想了解正在发生的事情,请将一些console.log('foobar');语句添加到您当前正在侦听的事件和fnAlertTitle函数中。届时您将能够更好地了解问题。 -
嗨@Raxi 感谢您的回复虽然使用
console.log没有问题,但我的要求需要使用警报 -
啊,这很好,但不要将它与
onfocus事件上的钩子结合使用,同时让(重新)触发alert()。这绝不是一个好主意。
标签: javascript html html5-history onfocus