[英]Making text singular or plural based on variable length
I am trying to make text singular or plural based on the value of templateCount
. 我试图根据
templateCount
的值使文本为单数或复数。 If templateCount
's value is 1 then I just want 'Template' to say that, but if templateCount
is plural, I want it to say 'Templates Selected'. 如果
templateCount
的值为1,那么我只想让'Template'这样说,但是如果templateCount
为复数,我希望它说为'Templates Selected'。
What am I doing wrong with my code? 我的代码在做什么错?
$('#templateCount').html(templateCount + " Templates Selected" + templateCount.length == 1 ? "" : "s");
Are you sure you thought this through? 您确定您已经考虑了吗? You have the string
"Templates selected"
there and you are conditionally appending s
to the end of that (which would make it "Templates Selecteds"
). 您在此处拥有字符串
"Templates selected"
,并且有条件地将s
附加到该字符串的末尾 (这将使其成为"Templates Selecteds"
)。
Do this: 做这个:
$('#templateCount').html(templateCount +
" Template" +
(templateCount === 1 ? "" : "s") +
" Selected");
I'm not sure if what you mean is that you want to put an 's' on the end if templateCount == 1 or if templateCount's length is 1. Those can be two very different things. 我不确定您的意思是是否要在templateCount == 1或templateCount的长度为1时在末尾添加“ s”。这可能是两个截然不同的事情。
If you want it based on the variable == 1, then I would try: 如果您希望基于变量== 1,那么我会尝试:
var templateCount;
// set it somewhere
var plural = templateCount === 1 ? "" : "s";
$('#templateCount').html(templateCount + " Template"+plural+ " Selected");
If it's the length you're actually after, change plural to 如果这是您实际需要的长度,请将复数更改为
var plural = templateCount.length > 1 ? "" : "s";
Try this 尝试这个
function makeStatement(templateCount) { return templateCount + " Template" + (templateCount == 1 ? "" : "s") +" Selected"; } console.log(makeStatement(1)); console.log(makeStatement(2));
And in your case 而你的情况
$('#templateCount').html(templateCount + " Template" + (templateCount == 1 ? "" : "s") + " Selected");
也许我读错了您的问题,但是您是否仅需要更改代码以使其看起来像这样?
$('#templateCount').html(templateCount + " Template" + (templateCount.length == 1 ? "" : "s") + " Selected");
Like this? 像这样?
var templateCount = [ 1 ]; function test() { var tmp = templateCount.length == 1 ? 1 : "Templates Selected"; $("#test").val(tmp); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="test"> <button onclick="test()">Test</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.