繁体   English   中英

根据可变长度使文本单数或复数

[英]Making text singular or plural based on variable length

我试图根据templateCount的值使文本为单数或复数。 如果templateCount的值为1,那么我只想让'Template'这样说,但是如果templateCount为复数,我希望它说为'Templates Selected'。

我的代码在做什么错?

$('#templateCount').html(templateCount + " Templates Selected" + templateCount.length == 1 ? "" : "s");

您确定您已经考虑了吗? 您在此处拥有字符串"Templates selected" ,并且有条件地将s附加到该字符串的末尾 (这将使其成为"Templates Selecteds" )。

做这个:

$('#templateCount').html(templateCount + 
    " Template" + 
    (templateCount === 1 ? "" : "s") +
    " Selected");

我不确定您的意思是是否要在templateCount == 1或templateCount的长度为1时在末尾添加“ s”。这可能是两个截然不同的事情。

如果您希望基于变量== 1,那么我会尝试:

var templateCount;
// set it somewhere
var plural = templateCount === 1 ? "" : "s";
$('#templateCount').html(templateCount + " Template"+plural+ " Selected");

如果这是您实际需要的长度,请将复数更改为

var plural = templateCount.length > 1 ? "" : "s";

尝试这个

 function makeStatement(templateCount) { return templateCount + " Template" + (templateCount == 1 ? "" : "s") +" Selected"; } console.log(makeStatement(1)); console.log(makeStatement(2)); 

而你的情况

$('#templateCount').html(templateCount + " Template" + (templateCount == 1 ? "" : "s") + " Selected");

也许我读错了您的问题,但是您是否仅需要更改代码以使其看起来像这样?

$('#templateCount').html(templateCount + " Template" + (templateCount.length == 1 ? "" : "s") + " Selected");

像这样?

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM