[英]single quotes breaking down the JavaScript String
When I put Single quote in text box, it does not show in dynamically added textbox. 当我在文本框中放置单引号时,它不会在动态添加的文本框中显示。 See following example :
请参阅以下示例:
$("#abc").before("<div><input type='text' value='" + $scope.txt + "'/></div>");
http://jsfiddle.net/U3pVM/15777/ http://jsfiddle.net/U3pVM/15777/
I've had a similar problem some time ago, and found this answer https://stackoverflow.com/a/9756789/2619170 我前段时间遇到过类似的问题,发现这个答案https://stackoverflow.com/a/9756789/2619170
See the quoteattr function, that's what you need: http://jsfiddle.net/U3pVM/15780/ 请参阅quoteattr函数,这就是您所需要的: http : //jsfiddle.net/U3pVM/15780/
function quoteattr(s, preserveCR) {
preserveCR = preserveCR ? ' ' : '\n';
return ('' + s) /* Forces the conversion to string. */
.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
/*
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);
;
}
Try this, I have assumed that you want "text with quote" as an input to be added and displayed without quotes. 试试这个,我假设你想要“带引号的文本”作为输入添加和显示没有引号。
function TodoCtrl($scope) {
$scope.txt = "";
$scope.addBefore = function() {
$("#abc").before("<div><input type=\"text\" value=" + $scope.txt + "></div>");
};
}
Try replacing _'_
by <code>&apos;<code>
, or _"_
by <code>&quot;<code>
尝试更换
_'_
通过<code>&apos;<code>
,或_"_
由<code>&quot;<code>
function TodoCtrl($scope) {
$scope.txt = "";
$scope.addBefore = function() {
$("#abc").before("<div><input type='text' value='" + $scope.txt.replace("'","'") + "'/></div>");
};
}
function TodoCtrl($scope) {
$scope.txt = "";
$scope.addBefore = function() {
$("#abc").before('<div><input type="text" value="' + $scope.txt + '"></div>');
};
}
just change from double to single 只是从双变为单
http://jsfiddle.net/U3pVM/15784/ http://jsfiddle.net/U3pVM/15784/
我通过用等效的HTML代码替换单引号或双引号来完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.