JS允许打印单引号和双引号



我在字符串内遇到单引号和双引号的问题。就我而言,它是:

var Des = "It's alright. We are the so-called "Vikings" from the north.";

我想按原样显示这个字符串。我有一个随机字符串。有时,它只有单引号,双引号,有时什么都没有。

到目前为止,我尝试的代码是:

var fieldData  = "<input type='text' name='desc' value='""+Desc+""'>";

但它不起作用。

您需要首先使用"转义Des字符串中的双引号。

然后,您需要对value属性进行 HTML 编码,以便字符串中的引号不会干扰分隔属性本身的引号。当你标记了jQuery时,你可以通过使用val()非常简单地做到这一点,因为它会为你编码值。试试这个:

var Des = "It's alright. We are the so-called "Vikings" from the north.";
var $input = $('<input type="text" name="desc">').val(Des);
$input.appendTo('body');
/* only used here to make the output fully visible without scrolling */
input { width: 325px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>