如何在javascript中向字符串添加占位符
我希望能够像这样轻松地为字符串设置默认占位符如何在javascript中向字符串添加占位符,javascript,string,Javascript,String,我希望能够像这样轻松地为字符串设置默认占位符 someString.placeholder("waiting for text") String.prototype.placeholder = function(placeholder){ return (this.length > 0) ? this : "<span class=\"placeholder-string\">" + placeholder + "</span>";
someString.placeholder("waiting for text")
String.prototype.placeholder = function(placeholder){
return (this.length > 0) ?
this :
"<span class=\"placeholder-string\">" + placeholder + "</span>";
}
可以这样使用
$("p.some-class").html( someString.placeholder("waiting for text") );
因此,如果“someString”为空,则用户会看到“正在等待文本”,但如果字符串的长度大于0,则用户会看到实际的字符串
我试着像这样扩展字符串对象
someString.placeholder("waiting for text")
String.prototype.placeholder = function(placeholder){
return (this.length > 0) ?
this :
"<span class=\"placeholder-string\">" + placeholder + "</span>";
}
String.prototype.placeholder=函数(占位符){
是否返回(此长度>0)?
这:
“+占位符+”;
}
但这似乎不起作用。有什么想法吗
这是给感兴趣的人的一个建议 似乎
此
是字符串
对象,而不是原始版本。你必须把它转换成原语。您还可以消除>0
:
String.prototype.placeholder = function(placeholder){
return this.length ?
this + "" :
"<span class=\"placeholder-string\">" + placeholder + "</span>";
}
String.prototype.placeholder=函数(占位符){
返回这个长度?
此+“”:
“+占位符+”;
}
如何将字符串输入到span
标记中?为什么?因为我想用css来设计它。因此,占位符会被稍微减少一些。使用逻辑OR:someString | |“等待文本”
?您定义的占位符方法称为placeholder
而不是placeholder
。我看不出有任何其他问题。占位符用于什么?他们到底是怎么把文字放进去的?可能是一些上下文和html?还有演示?