操作DOM时,Javascript是否同步? [英] Is Javascript synchronous when manipulating the DOM?

查看:142
本文介绍了操作DOM时,Javascript是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入类型字段的表单。我有几个单选按钮,根据我点击的是哪一个,输入类型字段中的值将被更新。之后,我将调用一个Javascript函数来执行某些操作,并且该函数将在输入字段中使用更新后的数量(文本)。



当然,它是将该数量传递给函数本身更安全,但是我可以依靠Javascript首先更新DOM,显示更新输入字段值,然后通过 document.getElementById(input-quantity ).value 并在函数中使用它?或者,如果DOM的刷新花费时间,函数能否获得旧值?解析方案

正如你所说的,只是将值传递给该函数将是首选。



但是,设置输入值是同步的;在您所描述的内容中,您将可靠地获得更新的价值,跨浏览器。其他的DOM操作(插入元素,删除它们,移动它们)也是同步的,尽管用户在JavaScript代码完成前可能看不到结果,让浏览器使用该线程重新绘制显示。 (虽然JavaScript本质上不是单线程的,但浏览器使用单个主UI线程来运行JavaScript代码,并且通常也使用该线程来更新显示。)


I have a form with an input of type field. I have several radiobuttons, and depending on which of them I click, the value in the input type field will be updated. After that, I will call a Javascript function to perform certain action, and the function will use the updated quantity (text) in the input field.

Of course, it is more secure to pass that quantity to the function itself, but could I rely on Javascript first updating the DOM, displaying the update input field value, and with that, retrieving it viadocument.getElementById("input-quantity").value and using this in the function? Or could the function get the "old" value if the refresh of the DOM takes its time?

解决方案

As you said, just passing the value to the function would be preferred.

But yes, setting the value of an input is synchronous; in what you describe, you will reliably get the updated value, cross-browser. Other DOM manipulations (inserting elements, removing them, moving them) are also synchronous, although the user may not see the result until your JavaScript code completes, letting the browser use the thread to repaint the display. (Although JavaScript is not inherently single-threaded, browsers use a single main UI thread to run your JavaScript code, and typically also use that thread to update the display.)

这篇关于操作DOM时,Javascript是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆