如何突出显示javascript列表框项?

时间:2014-03-09 14:02:13

标签: javascript

我有一个功能可以将选定的项目(列表框)中的所选项目与其上方的项目进行交换,但是我想这样做,以便在单词之后仍然选择该项目。因此,如果用户想要继续在框中向上移动项目,他可以继续按下“上移”按钮。

    function moveUp() {
        var list = document.getElementById('listbox');
        var numSelected = list.selectedIndex;
        var itemSelected = list.options;            

        if (itemSelected[numSelected].id == 0) {
            alert("Can't move this up the list!");
        } else {
            if (poiArrayList[numSelected - 1] != null) {
                var tempPOI = poiArrayList[numSelected];
                poiArrayList[numSelected] = poiArrayList[numSelected - 1];
                poiArrayList[numSelected - 1] = tempPOI;
                //The line below is what I have but that doesn't seem to work.
                list.selectedIndex = numSelected;
            } else {
                alert("The listbox is empty!");
            }
        }
    }

Full code

1 个答案:

答案 0 :(得分:1)

看看这里:http://jsfiddle.net/2ae9B/1/

我在generateListBox()添加了一个可选参数,您可以在其中设置生成列表后突出显示的索引。例如:

function moveUp() {
    var list = document.getElementById('listbox');
    var numSelected = list.selectedIndex;
    ...
    ...

    // regenerate the list passing the item to select
    generateListBox(numSelected - 1);
}

function generateListBox(selectedIndex) {
    var selectBox = document.getElementById("listbox");
    selectBox.innerHTML = "";
    for (var i = 0; i < poiArrayList.length; i++) {
        lbAddItem(poiArrayList[i].name, i);
    }

    // you should also check that is a valid integer here
    if(selectedIndex)
        selectBox.selectedIndex = selectedIndex;
}

希望有所帮助