我想创建一个包含以下内容的段落:名称、成本(如“3.66$”)。但问题是我想用点(“......”)填充空间,但我不知道如何。
我从数据库中获取值(名称和成本),每个名称都不同,所以我无法考虑如何使空间充满点。
例如,行:
"apple 20.58$"
"banana and ice cream 4.99$"
需要:
"apple ...................... 20.58$"
"banana and ice cream ........ 4.99$"
这是代码:
for (var i = 0; i < data.d.length; i++) {
$(document).ready(function () {
$("#ShowMenu").append(
"<p style='text-align: left;margin: 0px;'>" +
"<span style='font-size: large;font-weight: bold;float:left;'>" + data.d[i].title + "</span>" +
"<span style='float:right;'>" + data.d[i].cost + "</span>" +
"</p>"
);
});
}
最佳答案
If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).
Souce .
问题是替换替换了第一个找到的匹配项。你可以这样做:
function replaceAll(input, what, withWhat) {
while (input.indexOf(what) !== 0) {
input = input.replace(what, withWhat);
}
return input;
}
但这既不高效也不优雅。要改进它,需要使用正则表达式:
function replaceAll(input, what, withWhat) {
return input.replace(new RegExp(what, 'g'), withWhat);
}
并调用replaceAll
。如果你想让它变得更通用,你可以这样做:
String.prototype.replaceAll = replaceAll;
编辑:
上面的答案来自于文本是由 Javascript 生成的假设。从评论部分和问题编辑可以看出,我的假设是错误的。真实情况是由于使用 float
的 CSS 样式而出现空格。
一种可能的解决方案是创建一个点字符图像和另一个具有其他内容所需背景的图像。将段落的背景图片设置为带重复的点图,将跨度的背景图片设置为彩色图像。
另一种可能的解决方案是不使用 float ,而是使用 javascript 写入点,直到宽度达到所需的宽度。这涉及标签测量并且速度很慢。
关于javascript - 如何给段落填充内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703572/