[英]Does Crockford's "deentityify" method in The Good Parts actually work?
这个特定的代码之前曾被问过两次,但从来没有提出过“它实际上有什么作用?”的问题。 它出现在 Crockford 的书的第 41 页。
这是本书前面的语法糖:
Object.prototype = function (name, func){
if(!this.prototype[name]){
this.prototype[name] = func;
}
这是 deentityify 方法:
String.method('deentityify', function ( ) {
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
return function () {
return this.replace(
/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
如果在编辑器中你写的是这样的:
document.writeln( '<">'.deentityify( ));
您将在浏览器中看到:但是,如果您在浏览器中输入: document.writeln( '<">');
你仍然会看到:
<">
我发现当我尝试通过设置如下值字段来预填写表单数据时,此方法实际上并没有替换实体:
var venueInput = document.createElement("input");
...
venueName = '<>"'; // for example
venueInput.value = venueName.deentityify();
form.appendChild(venueName);
form.appendChild(venueInput);
警报还显示实体没有被替换。
谁能帮我看看我做错了什么? 谢谢!
在修复了您共享的代码的一些错误后,它就像一个魅力:
Object.prototype.method = function (name, func){ if(!this.prototype[name]){ this.prototype[name] = func; } } String.method('deentityify', function ( ) { var entity = { quot: '"', lt: '<', gt: '>' }; return function() { return this.replace( /&([^&;]+);/g, function (a, b) { var r = entity[b]; return typeof r === 'string' ? r : a; } ); }; }()); var venueInput = document.createElement("input"); var label = document.createElement("label"); venueName = '<>"'; // for example venueInput.value = venueName.deentityify(); label.innerHTML = venueName; document.getElementById('form').appendChild(label); document.getElementById('form').appendChild(venueInput);
<div id="form"></div>
这是本书前面的语法糖
你复制错了。 它应该是这样的:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
venueName = '<>"'; // for example
实体应以“;”结尾。 你忘记了报价上的那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.