无法获得动态添加的textarea的outerHTML /值 [英] Cannot get outerHTML/value of a dynamically added textarea

查看:171
本文介绍了无法获得动态添加的textarea的outerHTML /值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个小提琴 https://jsfiddle.net/xa9m49zy/ 表明您可以获得outerHTML(with文本区域值),但是当textarea动态添加到DOM时,outerHTML不包含文本区域值。它在Firefox和Chrome中不起作用,但它在IE和Edge中可用。

HTML:

 < textarea id =abc> ; 
测试
< / textarea>

JS:

 的console.log($( #ABC)得到(0).outerHTML。); //返回一切如预期的那样
$(< textarea id ='xyz'>< / textarea>).val(Test 2)。appendTo(body);
console.log($(#xyz)。get(0).outerHTML); //只显示< textarea>< / textarea>在非MS浏览器中

这是怎么回事?这是Chrome和Firefox中的错误吗?

解决方案

问题在于您正在设置第二个 textarea 使用 .val(),但 outerHTML 不检索值,它会检索元素和该元素的内容



textarea 元素从内容中获取它们的值。


如果为第二个 textarea 内容 >使用
.text()方法,它可以工作。

 警报($( #ABC)得到(0).outerHTML。); (#xyz); //返回所有预期的结果$(< textarea id ='xyz'>< / textarea>)。text(Test 2)。appendTo(body); alert($(#xyz )获得(0).outerHTML); //只显示< textarea>< / textarea>在非MS浏览器中 

< script src =https ://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js>< / script>< textarea id =abc>测试< / textarea>


This fiddle https://jsfiddle.net/xa9m49zy/ demonstrates that you can get the outerHTML (with the text area value) of a textarea that is in the DOM when it renders, but when the textarea is dynamically added to the DOM, the outerHTML doesn't contain the text area value. It doesn't work in Firefox and Chrome but it does work in IE and Edge.

HTML:

<textarea id="abc">
  Test
</textarea>

JS:

console.log($("#abc").get(0).outerHTML); //returns everything as expected
$("<textarea id='xyz'></textarea>").val("Test 2").appendTo("body");
console.log($("#xyz").get(0).outerHTML); //only shows <textarea></textarea> in non-MS browsers

What is going on here? Is this a bug in Chrome and Firefox?

解决方案

The problem is that you are setting the value of the second textarea using .val(), but outerHTML does not retrieve values, it retrieves an element and the content of that element.

textarea elements get their value from their content.

If you set the content for the second textarea using the .text() method, it works.

alert($("#abc").get(0).outerHTML); //returns everything as expected
$("<textarea id='xyz'></textarea>").text("Test 2").appendTo("body");
alert($("#xyz").get(0).outerHTML); //only shows <textarea></textarea> in non-MS browser

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="abc">
  Test
</textarea>

这篇关于无法获得动态添加的textarea的outerHTML /值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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