javascript javascript中的格式化字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12002861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
format string in javascript
提问by jongbanaag
Is it possible to achieve this in javascript?
是否可以在 javascript 中实现这一点?
Here is the format:
这是格式:
1 ITEM1 9.00 0% 9.00
1 ITEM-GET01 8.00 12% 5.00
I would like to create a receipt like layout. I'm using backbone.js so there will be models and collection involve.
我想创建一个像布局一样的收据。我正在使用backbone.js,所以会涉及模型和集合。
Also if it were on a table can I use jquery to get the data from the table tr
then have the result just like what is posted above?
另外,如果它在表上,我可以使用 jquery 从表中获取数据,tr
然后得到与上面发布的结果一样的结果吗?
I was able to read about sprintf but I don't think it it is the one I need. any ideas?
我能够阅读有关 sprintf 的信息,但我认为它不是我需要的。有任何想法吗?
UPDATE
更新
I'm trying out sprintf here is what i've come so far
我正在尝试 sprintf 这是我到目前为止所做的
var result = sprintf("%d %-s %.2f %d%% %.2f", model.get("Qty"), model.get("Itemname"), model.get("Price"), model.get("Discount"), model.get("ExtPrice"));
result is:
结果是:
1 Item1 1.49 0% 1.49
采纳答案by Snake Eyes
Read this article to use javascript similary sprintf in C...
阅读本文以在 C 中使用 javascript 类似 sprintf ...
http://www.webtoolkit.info/javascript-sprintf.html
http://www.webtoolkit.info/javascript-sprintf.html
or better read: JavaScript equivalent to printf/string.format
回答by Diode
You can do this in different ways. The method usually used is to loop in the data array and add rows in a table in which width of each column is set. Please see the sample in jQuery
你可以用不同的方式来做到这一点。通常使用的方法是在数据数组中循环并在设置了每列宽度的表中添加行。请参阅 jQuery 中的示例
var data = [
{
no: 1,
name: "ITEM1",
price1: "9.00",
perc: "0%",
price2: "9.00"},
{
no: 2,
name: "ITEM-GET01",
price1: "9.00",
perc: "12%",
price2: "5.00"}
];
//$("#list tr").remove();
$(data).each(function(index, item) {
$("#list").append('<tr><td width="50">' + item.no + '</td><td width="100">' + item.name + '</td><td width="100">' + item.price1 + '</td>' + item.perc + '<td width="100">' + item.price2 + '</td></tr>');
})