0

我仍在学习 javascript,我当前的应用程序有问题
从这个小提琴,它不起作用,但它可以大致显示我想要实现的目标。

如果我选择 Banana & Mouse,我的输出将是:
Banana is yellow
Mouse is small

我想知道如何通过单击按钮来调用第二个函数,以及如何在这种情况下重用我的代码,因为最后还有另外 5 个选择选项。

谢谢!

4

2 回答 2

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;;
}

演示

于 2013-01-07T19:21:16.670 回答
0

你可以让它更简单。但这是您正在寻找的链接

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;
}
于 2013-01-07T19:22:37.880 回答