如果输入了4个数字,请执行此操作,3执行此操作,2执行此操作,1执行此jquery操作

时间:2011-12-29 22:09:40

标签: jquery split calculator

我已经有了这个小工具 - http://jsfiddle.net/sturobson/reCjA/31/

我目前想要它,以便您可以在边距表单字段中输入CSS Margin简写并返回正确的结果。

if I enter 10, then I get a result of 10%
if I enter 10, 10 then I get a result of 10% 10%
if I enter 10, 10, 10 then I get a result of 10% 10% 10%
if I enter 10, 10, 10, 10 then I get a result of 10% 10% 10% 10%

如果我输入10,我得到10%0 0 0

我想要0但是只有所有四个数字都在那里。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

听起来像是一些条件逻辑的时候了。

var value = getFromText();
var pieces = value.split(",")
                  .map(function (piece) { return piece.trim(); })
                  .filter(function (piece) { return !!piece; });

var derivedPieces = (function () {
    switch (pieces.length) {
        case 0:
            return [];
        case 1:
            return [pieces[0], pieces[0], pieces[0], pieces[0]];
        case 2:
            return [pieces[0], pieces[1], pieces[0], pieces[1]];
        case 3:
            return [pieces[0], pieces[1], pieces[2], pieces[1]];
        case 4:
            return pieces;
        default:
            return [pieces[0], pieces[1], pieces[2], pieces[3]];
    }
}());

var withPercentSigns = derivedPieces.map(function (piece) { return piece + "%"; })
                                    .join(" ");

Working sample on JSFiddle

答案 1 :(得分:0)

对整数值进行评估,而不是字符串。

if (shorthand1 != '0'){
    shorthand1 += '%';
}    

...变为

if (shorthand1 != 0){
        shorthand1 += '%';
}

答案 2 :(得分:0)

使用数组中的.length属性(分割字段时获得的属性)和switch

相关问题