简体   繁体   English

jQuery:在Chrome中使用未转义的html填充textarea

[英]jquery: Fill textarea with unescaped html in Chrome

I am attempting to store html code in a textarea field using jquery with the following code: 我正在尝试使用带有以下代码的jquery将HTML代码存储在textarea字段中:

var text ="<p>Hello, my name is Sam</p>";
var textarea = d.createElement( 'textarea' ); // Creates textarea to store text
div.appendChild( textarea );
textarea.innerHTML  = text; 
// $("textarea").val(modified_clipboard_text); // same issue
console.log( textarea.innerHTML ); // output should not be escaped html

The issue is, html strings are transformed to escaped entities (at least in Chrome). 问题是,html字符串被转换为转义的实体(至少在Chrome中)。 For example: <p> is transformed to &lt;p&gt; 例如: <p>转换为&lt;p&gt;

You can use this function: 您可以使用此功能:

function htmlUnescape(encodedString){
    return $("<p/>").html(encodedString).text(); 
}

Like 喜欢

var text ="<p>Hello, my name is Sam</p>";
var textarea = d.createElement( 'textarea' ); // Creates textarea to store text
div.appendChild( textarea );
textarea.innerHTML  = text; 
// $("textarea").val(modified_clipboard_text); // same issue
console.log( htmlUnescape(textarea.innerHTML) ); // output should not be escaped html

JQuery solution jQuery解决方案

You're using jquery so why not using the magic : 您正在使用jquery,为什么不使用magic:

 var text ="<p>Hello, my name is Sam</p>"; $('#container').append('<textarea></textarea>'); $('#container textarea').val(text); $('#select-btn').click(function() { $('#container textarea').select(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='container'></div> </br> <button id='select-btn'>Select</button> 

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

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