在 Javascript 中使值复数(大于、小于)
我有以下代码:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
我试图将其输出如下:
单击一次:“我一直作弊1次。”
不止一次点击:“我欺骗了X次。”
-- 在“times”末尾加“s”。
计数器工作正常,这只是我遇到困难的使“时间”或“时间”正确显示的最后一部分。
有什么想法我做错了吗?
谢谢!
I have the following code:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
I'm trying to have it output as such:
Clicked once: "I cheated 1 whole time."
Clicked more than once: "I cheated X whole times."
-- With an 's' at the end of "times".
The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.
Any ideas what I'm doing wrong?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是您的问题:
total_click = 1
。尝试将其更改为total_click == 1
。我不明白为什么你在那里有这个条件,因为无论如何它都不会像你期望的那样工作。尝试$("#counter").text("我作弊了 " + total_click + " 整个时间" + ((total_click == 1) ? ' ' : 's '));
Here is your problem:
total_click = 1
. Try changing it tototal_click == 1
. I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try$("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1) ? ' ' : 's '));
您没有正确使用三元运算符,并且还将total_click 分配给1 而不是检查其值。我建议将其转移到一个函数中以简化事情。
然后将字符串更改为
Here's an 示例。
You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.
Then change the string to
Here's an example.
对于简单的情况使用建议的实现是可以的,但是它不会扩展到更大的问题集,并且不适用于多种语言(或者它会很快变得丑陋)。
考虑到这一点,我创建了一个非常简单的 JavaScript 库,可用于对几乎任何语言中的单词进行复数化。它透明地将 CLDR 数据库用于多个语言环境。它的 API 非常简约,集成也非常简单。它被称为众多。
我还写了一篇简短的介绍文章:《如何使用 JavaScript 将不同语言中的任何单词复数?< /a>».
请随意在您的项目中使用它。我也很高兴收到您的反馈!
It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).
With this in mind, I’ve created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It’s API is very minimalistic and integration is extremely simple. It’s called Numerous.
I’ve also written a small introduction article to it: «How to pluralize any word in different languages using JavaScript?».
Feel free to use it in your project. I will also be glad for your feedback on it!