textarea的下一个兄弟姐妹有什么问题? [英] What is wrong with the next sibling of the textarea?

查看:100
本文介绍了textarea的下一个兄弟姐妹有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当这个脚本插入到HTML文档中时,会导致奇怪的行为。显示的textarea元素在< br> 标记插入后(我已在Chrome 42中测试过)丢失了它的值:

  var text = document.createElement(textarea); 
document.body.appendChild(text);
text.value =text;
alert(value presents);
document.body.innerHTML + =< br>; //(*)
alert(value absents);

这是什么原因?

解决方案

更改此:

  document.body.innerHTML + =< br> ; b 




document.body.appendChild(使用document.createElement( BR));

这会将一个新元素添加到DOM中,而不是将所有DOM的内容替换为全部新元素。



当您这样做时:

  document.body .innerHTML + =< br>; 

它与此等价:

  var str = document.body.innerHTML; 
str + =< br>;
document.body.innerHTML = str;

因此,您将整个DOM转换为HTML字符串,字符串,然后用全新的HTML代替整个DOM,这将创建所有新元素。除了这样做的低效率之外,它还用不同的DOM元素替换了所有DOM元素,所以现在任何DOM引用或事件处理程序都会被破坏,并且任何动态更改对DOM中不反映在HTML中的元素将会丢失。


When this script is inserted into HTML document, it causes the strange behaviour. The shown textarea element losts its value after the <br> tag insertion (I've tested it in the Chrome 42):

var text = document.createElement("textarea");
document.body.appendChild(text);
text.value = "text";
alert("value presents");
document.body.innerHTML += "<br>"; //(*)
alert("value absents");

What is the reason for this?

解决方案

Change this:

document.body.innerHTML += "<br>";

to this:

document.body.appendChild(document.createElement("br"));

This will append a single new element to the DOM rather that replace the entire contents of your DOM with all new elements.

When you do this:

document.body.innerHTML += "<br>";

it is the equivalent of this:

var str = document.body.innerHTML;
str += "<br>";
document.body.innerHTML = str;

So, you are turning the entire body DOM into an HTML string, adding one thing onto the end of the string, then replacing the entire body DOM with a new piece of HTML which will create all new elements.

Besides the inefficiency of doing it this way, it also replaces all the DOM elements with different DOM elements so any DOM references or event handlers are now broken and any dynamic changes you made to DOM elements that aren't reflected in the HTML will be lost.

这篇关于textarea的下一个兄弟姐妹有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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