【问题标题】:exchanging values in a select list with jQuery使用 jQuery 在选择列表中交换值
【发布时间】:2014-02-27 12:18:35
【问题描述】:

我正在尝试在单击链接时将选择选项值与 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/

【问题讨论】:

  • 当您只想交换值时,您正在交换整个内部 HTML 内容。
  • 你需要解释你想做什么。你想交换每个选择的选项元素,还是只交换值?为什么其中一个选择中的所有选项都具有相同的值?

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


【解决方案1】:

我是一步一步写的,这样比较容易理解:

$("#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】:

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

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

    演示: http://jsfiddle.net/tchh2/2/

    【讨论】:

    • +1 如果你为detach()添加解释会很好
    • 当前示例中不需要,但optgroups 也可以在select 中找到。
    • @kapa 那么选择器应该稍微修改一下,就好像元素的ID变了一样。
    【解决方案3】:

    您正在替换 <select> 中的整个 HTML(每个选项)。只要每个 select 的选项数量相同且相互对应,就可以使用 selected 索引属性进行交换:

    $("#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

    【讨论】:

    • 选项数量相同,但实际值和属性集不同。查看 OP 提供的 JSFiddle。
    • @VisioN 公平点。但是 OP 可能不想移动元素本身,他们只想将每个选择更改为与另一个选择相对应的选项。我认为它不应该投反对票。
    • 我同意你的观点,但我没有反对你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2011-01-15
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多