我正在尝试在单击链接时与 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;
});
您的方法适用于将 DOM 元素转换为 HTML 并返回。问题是您会通过这种方式丢失重要信息,例如选择了
哪个元素(它存储在 DOM 属性中,而不是 HTML 属性中,它只是给出了起点)。
关于javascript - 使用 jQuery 交换选择列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068318/