简体   繁体   English

Javascript:将选定的焦点重置为要重新渲染的元素

[英]Javascript: Reset the selected focus on an element that is being rerendered

I'm using dust.js in order to render Javascript templates to HTML. 我正在使用dust.js以便将Javascript模板呈现为HTML。 Using dust.js, I've basically broken my page into template components, that are rerendered in response to certain events. 使用dust.js,我基本上将我的页面分成了模板组件,这些模板组件会响应某些事件而重新呈现。 One such component/template conceptually looks as follow: 这样的组件/模板在概念上如下所示:

[Label] [Input1] [Input2] [Input3] [标签] [输入1] [输入2] [输入3]

All 3 inputs in this component have an onBlur event which is used to recalculate the value of the other inputs and which in turn causes the template to rerender. 此组件中的所有3个输入都有一个onBlur事件,该事件用于重新计算其他输入的值,进而使模板重新呈现。 So for instance, if the user modified the value of Input1, both Input2 and Input3's values will be adjusted and rerendered. 因此,例如,如果用户修改了Input1的值,则Input2和Input3的值都将被调整并重新呈现。

The reason I rerender the template instead of just setting the values is that the template contains additional logic and elements that are rendered depending on the values (so for instance, certain values would result in an error message being rendered or an additional field being displayed). 我重新呈现模板而不是仅设置值的原因是该模板包含根据值呈现的其他逻辑和元素(例如,某些值将导致呈现错误消息或显示其他字段) 。

So far so good, but this causes a focus problem. 到目前为止还不错,但这会引起焦点问题。 Take for example if the user modifies Input1 and then clicks on Input2. 以用户是否修改Input1然后单击Input2为例。 The onBlur will trigger, I'll update the values of Input2 and Input3 and then rerender the template. onBlur将触发,我将更新Input2和Input3的值,然后重新呈现模板。 This in turn will cause the user's focus to be discarded, and they'll have to click on Input2 again. 反过来,这将导致用户的焦点被放弃,他们将不得不再次单击Input2。

I need a way to know that the user clicked on Input2 so that I can set the focus to it after the rerendering has been completed. 我需要一种方法来知道用户单击了Input2,以便在重新渲染完成后可以将焦点设置到它。 As the onBlur event triggers before onFocus, I can't think of any way to do this. 由于onBlur事件在onFocus之前触发,因此我想不出任何办法。

Is there any solution other than bypassing the template rendering? 除了绕过模板渲染之外,还有其他解决方案吗?

I had a similar problem. 我有一个类似的问题。 I solved it by delaying the "blur" event listener function with about 100ms, to allow the focus event on another input to fire before the blur handler starts rendering. 我通过将“模糊”事件侦听器功能延迟约100ms来解决此问题,以允许在模糊处理程序开始渲染之前触发另一个输入上的focus事件。

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

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