0

我想要不同的行为,具体取决于<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

4

5 回答 5

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
    }
}
于 2012-04-19T17:05:19.913 回答
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);">
于 2012-04-19T16:52:38.390 回答
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);
于 2012-04-19T16:48:11.520 回答
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
}
于 2012-04-19T16:50:58.140 回答
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在这里

于 2012-04-19T16:52:38.853 回答