简体   繁体   English

表单提交后重新设置焦点(javascript)

[英]Set focus back after form submit (javascript)

I have some input fields on my form that require submit on change. 我有需要提交一份关于改变我的表格上的一些输入字段。 When they are submitted I lose the focus. 当他们提交时,我失去了重点。 I want to have my focus back on my input. 我想把重点重新放在我的输入上。 I wanted to use that: 我想使用:

Event.observe(document, 'dom:loaded', $('" + focusedFieldId + "').focus());

where focusedFieldId is id of changed element. 其中focusFieldId是已更改元素的ID。 Sometimes it works fine but sometimes I got null value in my input. 有时它工作正常,但有时我在我的输入空值。 When I change focusedFieldId to some other field id it works fine (it sets the value and then focus on field). 当我将focusFieldId更改为其他字段ID时,它可以正常工作(它会设置值,然后将焦点放在字段上)。 The problem is only when I try set focus back on the same input. 问题仅在于当我尝试将焦点重新设置在同一输入上时。 One important issue: after value change some javascript is fired (http://www.devbridge.com/projects/autocomplete/prototype/). 一个重要的问题:值更改后,触发了一些JavaScript(http://www.devbridge.com/projects/autocomplete/prototype/)。 After this javascript form is submitted and then I want to set focus back. 提交此javascript表单后,我想重新设置焦点。 I thought that when dom is loaded it means that submit is over, page is reloaded and I'm ready to set focus back. 我认为加载dom时意味着提交已结束,页面已重新加载,我准备将焦点放回原处。 Where do I make mistake? 我在哪里犯错?

I believe you're falling in some sort of race condition here. 我相信您在这里陷入了某种竞赛状况。 There are two main, different "onLoad" events you can observe with prototype.js 您可以通过prototype.js观察到两个主要的不同“ onLoad”事件

One of them is what you just used here: 其中之一是您刚刚在这里使用的内容:

document.observe("dom:loaded", function() { ... });

another would be 另一个是

Event.observe(window, "load", function() { ... });

The first one will be executed as soon as the DOM (read: HTML) is loaded by the browser and the second when everything is loaded . 一个将在浏览器加载DOM(读取:HTML)后立即执行, 第二个将所有内容加载后执行

If you are setting your focusedFieldId in some script above that, I would strongly suggest going for the 2nd event observer; 如果您在上面的脚本中设置了focusedFieldId ,则强烈建议您使用第二个事件观察器; even though it's slower, it will make sure your previous scripts are parsed. 即使速度较慢,也可以确保您以前的脚本已被解析。

This still is a design flaw though. 但是,这仍然是设计缺陷。 I would strongly suggest you putting all of the screen controller logic (including the variable asignment) within the first onLoad event for much faster execution and avoid potential race conditions like this one. 我强烈建议您将所有屏幕控制器逻辑(包括变量赋值)放在第一个onLoad事件中,以加快执行速度,并避免此类潜在的竞争情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM