2013-01-07 90 views
0

我仍在學習JavaScript,並且我的當前應用程序有問題
從這個fiddle,它不起作用,但它可以大致顯示我想要實現的。對文本區域的多選擇

我的輸出,如果我選擇了香蕉&鼠標將是:
香蕉是黃色
鼠標小

我想知道我怎麼能叫的第二功能與按鈕只需點擊一下鼠標,以及如何我可以在這種情況下重複使用我的代碼,因爲我在結尾處還有另外5個選擇選項。

謝謝!

+0

解決:http://jsfiddle.net/jJCm3/5/。 – codingbiz

回答

0

您可以將ID作爲參數傳遞給函數,並相應地操作每個元素值。

function displayResult (fruitId,sizeId) { 
    var selTag = document.getElementById(fruitId); 
    var fruit=selTag.options[selTag.selectedIndex].text; 
    if (fruit=="Apple") { 
     fruit = fruit + " is red"; 
    } else if (fruit=="Orange") { 
     fruit = fruit + " is orange"; 
    } else if (fruit=="Banana") { 
     fruit = fruit + " is yellow"; 
    } 
    selTag = document.getElementById(sizeId); 
    var animal=selTag.options[selTag.selectedIndex].text; 
    if (animal=="Elephant") { 
     animal = animal + " is big"; 
    } else if (animal=="Mouse") { 
     animal = animal + " is small"; 
    } else if (animal=="Whale") { 
     animal = animal + " is enormous"; 
    } 
    document.getElementById('mytextbox').value = fruit+"\n"+animal;; 
} 

DEMO

+0

哦!現在我懂了!非常感謝穆薩! –

0

你可以使它更簡單。但這裏是你要找的東西a link

function displayResult (selId) { 
    var selTag = document.getElementById(selId); 
    var fruit=selTag.options[selTag.selectedIndex].text; 
if (fruit=="Apple") { 
    fruit = fruit + " is red"; 
} else if (fruit=="Orange") { 
    fruit = fruit + " is orange"; 
} else if (fruit=="Banana") { 
    fruit = fruit + " is yellow"; 
} 
    document.getElementById('mytextbox').value = fruit; 
    animalText(); 
} 

function animalText(){ 
    var selTag = document.getElementById("size"); 
    var _size=selTag.options[selTag.selectedIndex].text; 

    if (_size=="Elephant") { 
    _size = _size + " is big"; 
} else if (_size=="Mouse") { 
    _size = _size + " is small"; 
} else if (_size=="Whale") { 
    _size = _size + " is enormous"; 
} 

     document.getElementById('mytextbox').value = document.getElementById('mytextbox').value +"\n"+ _size; 
}