当选择框选项具有焦点时,Javascript事件不会触发

时间:2014-08-22 18:13:54

标签: javascript

当选择框选项具有焦点时,我正试图让事情发生(写入div)。从jsfiddle代码中,你可以看到我已经让它在事后工作了 - 也就是说,一旦选择了该选项并且鼠标移回到现在关闭的选择框。当盒子打开时,我该如何让它工作?

(如果重要的话,我有另一个函数绑定到同一个元素(选择框),触发'change'事件。我想知道这是不是问题?)。

HTML

<div id="Hint"></div>
<div id='select-container'>
    <select name="parent_selection" id="parent_selection">
        <option selected="selected">-- Select 1st option --</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>
    <select name="child_selection" id="child_selection">
        <option value="">-- Select 2nd option --</option>
    </select>
</div>

的JavaScript

//Display hint for hovered selection in 1st dropdown
var elSelect_container, elHint; // Declare variables

elAppSelected = document.getElementById('parent_selection');
elHint = document.getElementById('Hint');

function Hint() {
    var elAppSelected = this.options[this.selectedIndex].value;

    if (elAppSelected === 'option1') {
        elHint.innerHTML = 'Good choice';
    }
    if (elAppSelected === 'option2') {
        elHint.innerHTML = 'Better choice';
    }
    if (elAppSelected === 'option3') {
        elHint.innerHTML = 'Best Choice!';
    }
}
    //Create event listener: mouseover calls Hint()
    elAppSelected.addEventListener('mouseover', Hint, false);

http://jsfiddle.net/rpt613/a8hxa1jm/30/

1 个答案:

答案 0 :(得分:0)

我认为您的问题出在未显示的onchange事件中。我更改了addEventListener以更改vs鼠标悬停,示例工作正常。我不确定你需要另外的onchange事件,但也许你可以将它们结合起来。

JavaScript:

//Display hint for hovered selection in 1st dropdown
var elSelect_container, elHint; // Declare variables

elAppSelected = document.getElementById('parent_selection');
elHint = document.getElementById('Hint');

function Hint() {
    var elAppSelected = this.options[this.selectedIndex].value;

    if (elAppSelected === 'option1') {
        elHint.innerHTML = 'Good choice';
    }
    if (elAppSelected === 'option2') {
        elHint.innerHTML = 'Better choice';
    }
    if (elAppSelected === 'option3') {
        elHint.innerHTML = 'Best Choice!';
    }
}
    //Create event listener: mouseover calls Hint()
    elAppSelected.addEventListener('change', Hint, false);         
  //elAppSelected.addEventListener('mouseover', Hint, false);

http://jsfiddle.net/a8hxa1jm/31/