繁体   English   中英

如果文本框中的值大于1,则更改为复数

[英]Change to plural if value in textbox is greater than 1

我有一个文本框和一个选择框,如下所示:

<h3>Recipe Yield</h3>
<input style='width:100px' type="text" name="yield" class="small" />
<select name='yieldType'>
    <option value='Servings'>Serving(s)</option>
    <option value='Cups'>Cup(s)</option>
    <option value='Loaves (Loaf)'>Loaves (Loaf)</option>
</select>

这是一个JSFiddle: http : //jsfiddle.net/T3Sxb/

如您所见,选择选项为word(s)形式

但是我想要一个脚本,什么时候

  • 如果输入框中的数字为1,则选项中的值将为word形式
  • 如果输入框中的数字大于1,则选项中的值为复数。

这可能吗? 我怎样才能做到这一点? 感谢所有帮助!

我正在使用数据属性,以便您可以为每个项目声明适当的单数/复数形式。 在许多情况下,仅添加“ s”并不起作用。

还要注意,零项通常(总是?)采用复数形式。

的HTML

<input style='width:100px' type="text" id="yield" class="small" />
<select id='yieldType'>
    <option value='Servings' data-single="Serving" data-other="Servings"></option>
    <option value='Cups' data-single="Cup" data-other="Cups"></option>
    <option value='Loaves (Loaf)' data-single="Loaf" data-other="Loaves"></option>
</select>

的JavaScript

var yield = $("#yield");
var yieldType = $("#yieldType");

function evaluate(){
    var single = parseInt(yield.val(), 10) === 1;
    $("option", yieldType ).each(function(){
        var option = $(this);
        if(single){
            option.text(option.attr("data-single"));
        }else{
            option.text(option.attr("data-other"));
        }
    });
}

// whatever events you want to trigger the change should go here
yield.on("keyup", evaluate);

// evaluate onload
evaluate();

您可以尝试以下方法: http : //jsfiddle.net/T3Sxb/7/

var plural = {
    Serving: "Servings",
    Cup: "Cups",
    Loaf: "Loaves"
};

var singular = {
    Servings: "Serving",
    Cups: "Cup",
    Loaves: "Loaf"
};

$( "#pluralizer" ).on( "keyup keydown change", function() {
    var obj = parseInt( $( this ).val() ) === 1 ? singular : plural;
    $( "#YieldType option" ).each( function() {
        var html = $( this ).html();
        if ( html in obj ) {
            $( this ).html( obj[html] );
        }
    });
});

从用户体验的角度来看,我认为(s)是完全可以接受的。 但是无论如何,这是怎么回事:

<option value='Servings' data-singular="Serving" data-plural="Servings">Servings</option>

然后:

// you should really use IDs ;)
$('input[name="yield"]').on('change', function () {
    var singular = parseInt($(this).val(), 10) === 1;
    $('select[name="yieldType"]').each(function () {
        if (singular) {
            $(this).val($(this.attr('data-singular')));
        } else {
            $(this).val($(this.attr('data-plural')));
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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