单引号分解JavaScript字符串

时间:2015-05-22 06:03:28

标签: javascript jquery html

当我在文本框中放入单引号时,它不会显示在动态添加的文本框中。请参阅以下示例:

$("#abc").before("<div><input type='text' value='" + $scope.txt + "'/></div>");

http://jsfiddle.net/U3pVM/15777/

5 个答案:

答案 0 :(得分:3)

前段时间我遇到过类似问题,并找到了这个答案https://stackoverflow.com/a/9756789/2619170

请参阅quoteattr函数,这就是您所需要的:http://jsfiddle.net/U3pVM/15780/

function quoteattr(s, preserveCR) {
    preserveCR = preserveCR ? '&#13;' : '\n';
    return ('' + s) /* Forces the conversion to string. */
        .replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
        .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        /*
        You may add other replacements here for HTML only 
        (but it's not necessary).
        Or for XML, only if the named entities are defined in its DTD.
        */ 
        .replace(/\r\n/g, preserveCR) /* Must be before the next replacement. */
        .replace(/[\r\n]/g, preserveCR);
        ;
}

答案 1 :(得分:0)

试试这个,我假设你想要&#34;带引号的文字&#34;作为无需引号添加和显示的输入。

 function TodoCtrl($scope) {
  $scope.txt = "";
    $scope.addBefore = function() {
        $("#abc").before("<div><input type=\"text\" value=" + $scope.txt + "></div>");
    };
}

答案 2 :(得分:0)

尝试将_'_替换为<code>&ampapos;<code>,或_"_替换<code>&ampquot;<code>

JSFiddle

    function TodoCtrl($scope) {
     $scope.txt = "";
     $scope.addBefore = function() {
        $("#abc").before("<div><input type='text' value='" + $scope.txt.replace("'","&apos;") + "'/></div>");
    };
}

答案 3 :(得分:0)

function TodoCtrl($scope) {
  $scope.txt = "";
    $scope.addBefore = function() {
        $("#abc").before('<div><input type="text" value="' + $scope.txt + '"></div>');
    };
}

只需从双变为单

http://jsfiddle.net/U3pVM/15784/

答案 4 :(得分:0)

我通过用等效的HTML代码替换单引号或双引号来完成此操作。

相关问题