2011-09-17 77 views

回答

0
  1. 您不要使用}停止功能printColorAndGroup
  2. 对于键/值对而不是数组,您应该使用对象
  3. 您可能想要使用对象的文字表示法。
  4. onchange函数中,您可以通过选择this。因此,select.options[...]将是可能的和更清洁。
  5. 除了名称之外,您还可以使用ID,因此您无需每次都担心[0]

修改过的版本:http://jsfiddle.net/pimvdb/RemPF/1/


这是一个文本对象符号:

var colors = { apple: "red", 
       grape: "purple", 
       milk: "white", 
       cheese: "yellow", 
       chicken: "white", 
       beef: "red" }; 

这是标识是如何工作的:

<input type="text" id="food_group" ...> 

你可以获取与元素:

document.getElementById('food_group') 

这是如何通过选择作品:

<select name="food" onchange="printColorAndGroup(this)"> 

与以下JavaScript:

function printColorAndGroup(select){ 
var text = select.options[select.selectedIndex].value; 
... 
+0

非常感谢你..是的,我错过了大括号对不起。..你是非常有益的..再次感谢.. –

+0

哦,顺便说一下,这似乎是不与IE浏览器,它在Chorme ..不知道为什么,可以帮助我呢?我试过在IE 9 .. –

+0

@Raam:不知道,在IE9中为我工作。 – pimvdb

0

你错过关闭} </script>标签

function printColorAndGroup(){ 
    var text = document.getElementsByName('food')[0].options[document.getElementsByName('food')[0].selectedIndex].value; 
    document.getElementsByName('food_group')[0].value = groups[text]; 
    document.getElementsByName('food_color')[0].value = colors[text]; 
} 
相关问题