簡體   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