textarea的多重选择选项

时间:2013-01-07 19:06:56

标签: javascript

我还在学习javascript,我的当前申请有问题 从fiddle开始,它不起作用,但它可以粗略地显示我想要实现的目标。

如果我选择Banana&鼠标将是:
香蕉是黄色的 鼠标很小

我想知道如何只需单击一下按钮即可调用第二个函数,在这种情况下如何重用我的代码,因为我还有另外5个选择选项。

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
}