从选定或活动的ul li中捕获值

时间:2013-12-20 21:48:20

标签: javascript

我有以下代码,我试图在任何给定时间从列表中选择的任何值(。结果)中捕获值:

var active = document.querySelector(".hover") ||             document.querySelector(".the_results li");

document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);

function handler(e){
console.log(e.which);
    active.classList.remove("hover");
if (e.which == 40){
    active = active.nextElementSibling || active;

    document.getElementById("MyElement").value=(What goes inside here);
}else if (e.which == 38){      
    active = active.previousElementSibling || active;

}else{
    active = e.target;
}
    active.classList.add("hover");

}

我需要帮助:

document.getElementById("MyElement").value=(What goes inside here);

提前感谢您的帮助,因为我的想法已经用完了。

1 个答案:

答案 0 :(得分:1)

document.getElementById("MyElement").value = active.innerHTML;

我还添加了条件if (e.target.tagName === 'LI')。这是整个重构的片段:

function handler(e) {
    console.log(e.which);
    active.classList.remove("hover");
    if (e.which == 40) {
        active = active.nextElementSibling || active;     
    } else if (e.which == 38) {
        active = active.previousElementSibling || active;
    } else {
        active = e.target;
    }
    if (e.target.tagName === 'LI') {
        document.getElementById("MyElement").value = active.innerHTML;
    }
    active.classList.add("hover");
}

演示:http://jsfiddle.net/9zXmr/