使用jQuery在选择列表中交换值

时间:2014-02-27 12:18:35

标签: javascript jquery forms html-select dom-manipulation

当点击链接时,我正在尝试用jQuery交换选择选项值,此时它只是在链接点击时重置选择,不确定出现了什么问题?:

jQuery的:

$(function () {
    $("#swapCurrency").click(function (e) {
        var selectOne = $("#currency-from").html();
        var selectTwo = $("#currency-to").html();
        $("#currency-from").html(selectTwo);
        $("#currency-to").html(selectOne);
        return false;
    });
});

JS小提琴:http://jsfiddle.net/tchh2/

3 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为您从<select>个字段中删除了所有元素并将其再次设置为新元素。为了使其按预期工作,您最好移动实际元素,如下所示:

$("#swapCurrency").click(function(e) {
    var options = $("#currency-from > option").detach();
    $("#currency-to > option").appendTo("#currency-from");
    $("#currency-to").append(options);
    return false;
});

DEMO: http://jsfiddle.net/tchh2/2/

答案 1 :(得分:2)

我是一步一步地写的,所以更容易理解:

$("#swapCurrency").click(function (e) {

    //get the DOM elements for the selects, store them into variables
    var selectOne = $("#currency-from");
    var selectTwo = $("#currency-to");

    //get all the direct children of the selects (option or optgroup elements)
    //and remove them from the DOM but keep events and data (detach)
    //and store them into variables
    //after this, both selects will be empty
    var childrenOne = selectOne.children().detach();
    var childrenTwo = selectTwo.children().detach();

    //put the children into their new home
    childrenOne.appendTo(selectTwo);
    childrenTwo.appendTo(selectOne);

    return false;
});

jsFiddle Demo

您的方法适用于将DOM元素转换为HTML并返回。问题是你以这种方式丢失重要信息,比如哪个元素是selected(它存储在DOM属性中,而不是HTML属性,它只是给出了起点)。

答案 2 :(得分:0)

您正在替换<select>中的整个HTML(每个选项)。只要每个选项具有相同数量的选项并且它们彼此对应,您就可以使用所选的索引属性来交换它们:

$("#swapCurrency").click(function (e) {
    var selOne = document.getElementById('currency-from'),
        selTwo = document.getElementById('currency-to');
    var selectOne = selOne.selectedIndex;
    var selectTwo = selTwo.selectedIndex;
    selOne.selectedIndex = selectTwo;
    selTwo.selectedIndex = selectOne;
    return false;
});

JSFiddle