假设我有 2 个输入元素,只有 1 个按钮。我希望按钮根据当前正在聚焦的输入元素一次为一个输入元素执行一项功能,但我不知道如何捕获每个元素的聚焦状态。
请考虑这个例子:
<head>
<script type="text/javascript">
var id_box = document.createElement('input');
id_box.id = 'id_box';
id_box.type = 'text';
div.appendChild(id_box);
var weight_box = document.createElement('input');
weight_box.id = 'weight_box';
weight_box.type = 'text';
div.appendChild(weight_box);
function showLetter() {
if (id_box is being focused){
document.getElementById('id_box').value = 'ABC';
}
if (weight_box is being focused){
document.getElementById('weight_box').value = 'ABC';
}
}
</script>
</head>
<body>
<button onclick="showLetter()">ABC</button>
</body>
有什么想法吗?非常感谢。
最佳答案
单击按钮的那一刻,文本字段无论如何都会失去焦点。 try catch 每个文本框的 OnFocus 方法,并将变量设置为文本字段的实例。这样您就拥有最新的文本字段,并且不需要 if 语句。
关于Javascript:如何使用相同的按钮进行不同的文本输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5955583/