首页 > 解决方案 > 使用 Javascript 对 HTML 选择进行排序。参数不起作用

问题描述

我有 2 个选择。我想在它们之间移动项目。它们应该被分类。我从 SO 中获取了一些代码,并且遇到了一些奇怪的事情。当我将元素作为参数传递给排序函数时,它不起作用。当我在排序函数中明确获取元素时,它可以完美运行。看看排序函数的第一行,你就会明白我在说什么。

这是我的 PHP 部分。

   echo "
    <div><select id='listBox1' class='form-control select-manage-category' size='5'>
        <option value=1>1-text</option>
        <option value=2>2-text</option>
        <option value=3>3-text</option>
        <option value=4>4-text</option>
    </select></div>

    <input id='add-category' onclick='ClickAdd()'  name='add' type='button' value='Add Item'>
    <input id='remove-category' onclick='ClickRemove()' name='add' type='button' value='Remove Item'>

    <div>
        <select id='listBox2' class='form-group percent-100' size='5'></select>
    </div>
    ";
    
    echo "<script>";
    include 'bstest.js';
    echo "</script>";

而且,这是我的 JS (bstest.js)。


function ClickAdd() 
{
    // get the 'left' listbox.
    var e = document.getElementById('listBox1');

    // get the text and value of selected item.
    var eText = e.options[e.selectedIndex].text;
    var eVal = e.value;
        
    // create the new element
    var opt = document.createElement('option');     
    opt.text = eText;
    opt.value = eVal;       
        
    // add it to the 'right' listbox.
    document.getElementById('listBox2').options.add(opt);
        
    // now remove it from the 'left' list.
    value = e.selectedIndex;
    e.removeChild(e[value]);
    
    sortSelect(e);
    
}

function ClickRemove()
{
    // get the 'right' listbox.
    var e = document.getElementById('listBox2');
    
    // get the text and value of selected item.
    var eText = e.options[e.selectedIndex].text;
    var eVal = e.value;

    // create the new element
    var opt = document.createElement('option');     
    opt.text = eText;
    opt.value = eVal;       

    // add it to the 'left' listbox.
    document.getElementById('listBox1').options.add(opt);

    // now remove it from the 'right' list.
    value = e.selectedIndex;
    e.removeChild(e[value]);
    
    sortSelect(e);
}

function sortSelect(selectToSort) 
{
    
    //selectToSort = document.getElementById('listBox1');       // works.  If I comment it, it doesn't work.

    var arrOptions = [];
    for (var i = 0; i < selectToSort.options.length; i++)  
    {
        arrOptions[i] = [];
        arrOptions[i][0] = selectToSort.options[i].value;
        arrOptions[i][1] = selectToSort.options[i].text;
        arrOptions[i][2] = selectToSort.options[i].selected;
    }
    arrOptions.sort();
    for (var i = 0; i < selectToSort.options.length; i++)  
    {
        selectToSort.options[i].value = arrOptions[i][0];
        selectToSort.options[i].text = arrOptions[i][1];
        selectToSort.options[i].selected = arrOptions[i][2];
    }
    return;
}

标签: javascripthtmlsortingoption

解决方案


推荐阅读