如何在2个选择元素中交换选择的选项? [英] How to swap selected option in 2 select elements?

查看:86
本文介绍了如何在2个选择元素中交换选择的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮时,我使用2个select元素,并且不能在select字段中交换城市:

I use 2 select element and i can't swap the cities in the select field, when the button is clicked:

<div class="select-wrapper">
    <select class="airport-select__departure">
        <option value="1" selected>London(LGW)</option>
        <option value='2'>Paris(SHG)</option>
        <option value='3'>Vancouver(VAI)</option>
    </select>
    <button class="select-swap">&nbsp;</button>
</div>

<select class="airport-select__arrival">
    <option value='1' selected>New York(JFK)</option>
    <option value='2'>London(LGW)</option>
    <option value='3'>Vancouver(VAI)</option>
</select>

推荐答案

首先,逻辑步骤是:
1-两个列表必须具有完全相同的数据(值和文本),才能进行交换.
2-将Click事件处理程序添加到按钮.如下.

First The logical steps are:
1- both lists have to be same data exact (value and text) to be able for swapping.
2- Add the Click event Handler to the button. as following..

第二个代码:


jQuery:


JQuery:

$(document).ready(function() {
    $(".select-swap").on('click', function (ev) {
        swaper();
    });
});

function swaper () {
    var co=$(".airport-select__departure").val();
    $(".airport-select__departure").val($(".airport-select__arrival").val());
    $(".airport-select__arrival").val(co);
}


HTML:


HTML:

<div class="select-wrapper">
    <select class="airport-select__departure">
        <option value='1' selected>London(LGW)</option>
        <option value='2'>New York(JFK)</option>
        <option value='3'>Paris(SHG)</option>
        <option value='4'>Vancouver(VAI)</option>
    </select>
    <button class="select-swap">&nbsp;</button>
</div>
<select class="airport-select__arrival">
    <option value='1'>London(LGW)</option>
    <option value='2' selected>New York(JFK)</option>
    <option value='3'>Paris(SHG)</option>
    <option value='4'>Vancouver(VAI)</option>
</select>

这篇关于如何在2个选择元素中交换选择的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆