javascript - 使用 jQuery 交换选择列表中的值

标签 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 fiddle 在这里:http://jsfiddle.net/tchh2/

最佳答案

我按照步骤的方式写了它,这样更容易理解:

$("#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 并返回。问题是您会通过这种方式丢失重要信息,例如选择了哪个元素(它存储在 DOM 属性中,而不是 HTML 属性中,它只是给出了起点)。

关于javascript - 使用 jQuery 交换选择列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068318/

相关文章:

asp.net - 使用 Javascript 翻转文本框的只读标志

javascript - 使用 jQuery 启用和禁用复选框

jquery - 玩框架,jquery ajax调用冲突

php - 在 html 中发布带有 javascript 和 php 验证的表单。一个错误 - 返回 true 或 false 进入表单的文本框

html - 当文本区域处于焦点时,如何让 div 出现? (两者都是同一表单元素的子元素)

javascript - 为什么我会得到未定义错误的属性?

javascript - 从 json 数组中删除一些数据

javascript - 通过单击切换 div 来关闭我的#overlay 和侧菜单?

javascript - 简单的jquery验证——自定义位置错误信息放置

javascript - Web 表单 Azure Active Directory : Failed to load resource: the server responded with a status of 401