2015-05-15 43 views
0

說,我有以下字符串:如何生成一組字符串,並用另一個乘以每個字符串的jQuery

a = 5 
b = 6 
c = 7 

和我有兩個文本框: 代碼 碼值

問題是,我如何生成(a,b,c)的唯一字符串,並將它們添加到文本框的「代碼」中,並將每個字符串相互相乘並將它們添加到文本框'代碼值'

例如let say我生成了:

"cba" 

然後彼此相乘的每個值是這樣的:

7 * 6 * 5 = 210. 

即,「代碼」文本框將等於「CBA」 和「代碼值」文本框將平等到「210」。 我怎樣才能做到這一點?``

+0

請詳細說明「a」,「b」和「c」的來源。他們是變數嗎?還是頁面元素? – Taplar

+0

他們是變量 –

回答

0

如果您的變量將永遠是一個字母,你可以做

if(code.length){ 
    var result = eval(code[0]); 
    for(var i = 1; i < code.length; i++){ 
     var temp = eval(eval('code[i]')); 
     result = eval('temp*result'); 
    } 
    console.log(result); 
} 

看到它在action

1

設置它與對象,所以你可以定義每個字母的值,如果需要的話。然後嘗試循環每個字母並獲取其數值乘以。這裏是一個DEMO

var o = { // Define Letter Values 
    a: 1, 
    b: 2, 
    c: 3, 
    d: 4, 
    e: 5, 
    f: 6, 
    g: 7, 
    h: 8, 
    i: 9, 
    j: 10, 
    k: 11, 
    l: 12, 
    m: 13, 
    n: 14, 
    o: 15, 
    p: 16, 
    q: 17, 
    r: 18, 
    s: 19, 
    t: 20, 
    u: 21, 
    v: 22, 
    w: 23, 
    x: 24, 
    y: 25, 
    z: 26 
}; 

$('input').on('keyup', function(){ // Set whatever event you want to trigger the function 
    var str = $(this).val();  // Grab the string value 
    var arr = str.split('');  // Split the string on every letter into an array 
    var total = 0; 
    $.each(arr, function(i, v){  // Loop through the letters 
     var letterIndex = o[v];  // Get the numerical value of the current letter 
     if(i === 0){    // If this is the first letter set the starting letter value 
      total = letterIndex; 
     } else {     // Else multiply the current total by the letter's value 
      total = total * letterIndex; 
     } 
    }); 
    $('#yourOtherTextarea').val(total);   // Do whatever you want with the results 
}); 

希望這有助於!如果您有任何問題,請告訴我。

+0

非常感謝,它的工作就像魔術....一件事,我將如何顯示結果,因爲我在另一個文本框中鍵入 –

+0

我相信你可以將事件從'更改'更改爲'鍵入',然後添加另一個textarea,而不是div上的.html(),在新的textarea上運行.val(total)。 – wrxsti

+0

更新了答案以反映這一點。不要忘記標記爲正確的答案!謝謝! :) – wrxsti

相關問題