如何将选项传递给HTML选择

时间:2012-04-19 16:40:59

标签: javascript dhtml

根据选择的<option>元素,我想要不同的行为:

<select name="colorSelector" onchange="handleColorChange();">
    <option value="">- select -</option>
    <option value="1">Red</option>
    <option value="2">Blue</option>
</select>

function handleColorChange() {
    // Behave different depending on which <option> was just selected
}

我需要从handleColorChange()侦听器内部传递onchange方法才能完成此操作?

5 个答案:

答案 0 :(得分:2)

看起来还没有人提到switch。另外,不要把功能放在HTML中,这很糟糕。这是正确的方法:

document.getElementsByName( 'colorSelector' )[ 0 ].onchange = function ( ) {
    switch ( this.options[ this.selectedIndex ].value ) {
        case '1':
            // Do something when "Red" is selected
            break
        case '2':
            // Do something when "Blue" is selected
            break
    }
}

答案 1 :(得分:1)

尝试

function handleColorChange(self)
{
   console.log(self.selectedIndex);
   console.log(self.options[self.selectedIndex].text);
   console.log(self.options[self.selectedIndex].value)
};

并在HTML代码中

<select id="mySelect" name="colorSelector" onchange="handleColorChange(this);">

答案 2 :(得分:0)

你不必传递任何东西来运作,只需指定一个id来选择:

<select id="mySelect" name="colorSelector" onchange="handleColorChange();">
    <option value="">- select -</option>
    <option value="1">Red</option>
    <option value="2">Blue</option>
</select>

function handleColorChange() {
var x=document.getElementById("mySelect").selectedIndex;
var y=document.getElementById("mySelect").options;
alert("Index: " + y[x].index + " is " + y[x].text);
}

或者如果您想通过名字获取,请在您的函数中执行此操作:

var x=document.getElementsByName("colorSelector")[0].selectedIndex;
var y=document.getElementsByName("colorSelector")[0].options;
alert("Index: " + y[x].index + " is " + y[x].text);

答案 3 :(得分:0)

使用this

<select name="colorSelector" onchange="handleColorChange(this);">
    <option value="">- select -</option>
    <option value="1">Red</option>
    <option value="2">Blue</option>
</select>

function handleColorChange(element) {
    // Behave different depending on which <option> was just selected
}

答案 4 :(得分:0)

<select name="colorSelector" onchange="handleColorChange(this);">
    <option value="">- select -</option>
    <option value="1">Red</option>
    <option value="2">Blue</option>
</select>​


function handleColorChange(obj) {
    alert(obj.options[obj.selectedIndex].value);
}​

JSFiddle here