2011-12-29 36 views
0

我有這個小計算器我的工作 - http://jsfiddle.net/sturobson/reCjA/31/如果4號進入這樣做,3爲此,2做到這一點,1做這個jQuery

我目前想它,這樣你可以在保證金錶單域中輸入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,但只有當所有四個數字在那裏。

任何想法?

+0

如果你在一個文本框中輸入這些數字,分裂他們的逗號,並通過陣列構建的最終結果進行迭代。 – Dimitri 2011-12-29 22:12:52

+0

呃?這已經從我找到,玩過並'借來'的片斷合併在一起我不確定如何去做你在想什麼:/ – 2011-12-29 22:16:05

+0

它看起來像你原來的小提琴的作品...? http://jsfiddle.net/sturobson/reCjA/ – BZink 2011-12-29 22:18:45

回答

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

+0

這看起來像我需要做的:o) – 2011-12-29 22:20:11

+0

我需要改變什麼位才能在我的小提琴中工作?件=邊際? – 2011-12-29 22:30:03

+0

你也是小提琴演出什麼我鍵入的結果4? :/ – 2011-12-29 22:31:12

0

做對整數值,而不是字符串的評估。

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

成爲...

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

在JavaScript中,這些是等價的,只要你使用'!='而不是'!=='。 – Domenic 2011-12-29 22:17:59

+0

不是根據小提琴的結果。進行更改,結果發生變化。 – BZink 2011-12-29 22:22:56

+0

啊,我明白了爲什麼。這是因爲'「」!=「0」'是'true',但'「」!= 0'是'false'。不是真正解決問題根源的方法......但是如果StackOverflow允許我>: – Domenic 2011-12-29 22:25:32

0

使用在你的陣列(那些你當你分割一個場)與switch沿.length財產。

相關問題