[英]Prevent javascript from auto escaping & character
I am seeing &
我看到
&
in my textbox but I only want &
. 在我的文本框中,但我只想要
&
。 I think it is something to do with the way browser interpret javascript .innerHTML
. 我认为这与浏览器解释javascript
.innerHTML
。 The text with &
must pass through div. 带
&
的文本必须通过div。 For some reason, I can't directly assign value to the text box. 出于某种原因,我不能直接为文本框赋值。
HTML Code HTML代码
<div id='div'></div>
<input id='textbox' type='text' />
Javascript Code Javascript代码
var str = 'this & char';
$('#div').append("<div>" + str + "</div>");
$('#textbox').val($('#div').html());
Actual HTML output 实际的HTML输出
<div>this & char</div>
and user sees this & char
并且用户看到
this & char
this & char
in textbox. 文本框中的
this & char
。
Desire HTML output 渴望HTML输出
<div>this & char</div>
and user sees this & char
in textbox. 用户在文本框中看到
this & char
。
You're using .html()
which is the reason the &
gets translated to &
你正在使用
.html()
这就是&
被转换为&
的原因&
. 。 Since it's an input, it must be in plain text and hence, when you write
&
由于它是一个输入,它必须是纯文本,因此,当你写
&
in an input field, it's displayed as a text. 在输入字段中,它显示为文本。
$('#textbox').val($('#div').text());
Instead of using html()
use text()
. 而不是使用
html()
使用text()
。 html()
treats the string as HTML, text()
treats the content as text. html()
将字符串视为HTML, text()
将内容视为文本。
var str = 'this & char'; $('#div').append("<div>" + str + "</div>"); $('#textbox').val($('#div').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='div'></div> <input id='textbox' type='text' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.