How does form value caching work in browsers?

南楼画角 提交于 2019-12-24 02:13:08

问题


I've read somewhere in a documentation that most browsers don't update DOM as form values change, because frequent DOM manipulation need heavy computing performance. Instead, they create a cache of form values to register form manipulation, and only update the DOM when a the form is submitted.

Do browsers really work this way? Is there an extensive documentation about this behavior?


回答1:


DOM elements have properties and attributes.

If you change an attribute e.g. the value="" then the DOM is changed.
But the current value of a form element is stored in the property value and this is the one that is changed when the user types something e.g. into an input field.

If the attribute changes the css rules needs to be rechecked if some don't apply anymore or some others will apply now.

Here a little example:

CSS

[value='foo'] {
    color: red;
}

[value='bar'] {
    color: green;
}

HTML

<input id="text-element" type="text" value="foo"><br>

<a href="#" id="prop-change">prop-change</a>
<a href="#" id="attr-change">attr-change</a>

JS

document.getElementById("attr-change").onclick = function() {
    document.getElementById("text-element").setAttribute("value","bar");
    return false;
};

document.getElementById("prop-change").onclick  = function(e) {
    document.getElementById("text-element").value = "bar";
    return false;
};

Live Demo (JSFiddle)

If you try this in current FireFox or Chrome and type bar or click on prop-change the color is not changing to green.

But if you click on attr-change it turns green because the attribute changes.

Additionally if you reload and type e.g. test into it and then press attr-change you see that it will turn green but test will still be the current value.



来源:https://stackoverflow.com/questions/18917922/how-does-form-value-caching-work-in-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!