Javascript:如何使用相同的按钮进行不同的文本输入?
假设我有 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>
有什么想法吗?非常感谢。
Suppose I have 2 input elements with only 1 button. I want the button to do a function for one input element at a time according to which one is currently being focused but I don't know how to capture focusing status of each element.
Please consider this example:
<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>
Any idea? Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(4)
单击按钮的那一刻,文本字段无论如何都会失去焦点。尝试捕获每个文本框的 OnFocus 方法,并将变量设置为文本字段的实例。这样您就拥有最新的文本字段,并且不需要 if 语句。
The minute you click the button, the textfield loses focus anyway. Try trapping the OnFocus method for each text box and set a variable to the instance of the textfield. This way you have the latest text field and you don't need your if statement.
如果输入具有焦点,并且用户随后单击按钮,则输入将立即失去焦点,因此您无法按照您想要的方式检测哪个输入具有焦点。
您可以通过将事件处理程序附加到 onFocus 事件的每个输入来创建一个存储“当前”输入的变量。
jsFiddle 演示:http://jsfiddle.net/P58sx/1/
If an input has focus and if the user then clicks a button the input will lose focus instantly so you cannot detect which input has focus in the way you want.
You could create a variable that stores the "current" input by attaching an event handler to each input for the
onFocus
event.Demo on jsFiddle: http://jsfiddle.net/P58sx/1/
我建议尝试
onFocus
事件处理程序。I would recommend trying the
onFocus
event handler.一个技巧是声明一个变量并将其设置在每个字段的 onFocus 事件中。然后,在按钮代码中,您可以检查单击按钮之前聚焦的最后一个字段是什么。
One trick would be to declare a variable and setting it in
onFocus
event of each field. Then in the button code you can check what was the last field that was focused before the click on the button.