gpt4 book ai didi

javascript - 如何反转两个输入选择之间的选项值?

转载 作者:行者123 更新时间:2023-11-27 22:58:43 25 4
gpt4 key购买 nike

我有两个输入选择,具有相同的选项。单击触发器时,我需要反转这两个选择之间的选项值。例如:

<select id="source_currency">
<option value="BRL" selected>BRL</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
</select>

<select id="target_currency">
<option value="BRL">BRL</option>
<option value="USD">USD</option>
<option value="EUR" selected>EUR</option>
</select>

我需要的是通过点击触发器发生这样的事情:

<select id="source_currency">
<option value="BRL">BRL</option>
<option value="USD">USD</option>
<option value="EUR" selected>EUR</option>
</select>

<select id="target_currency">
<option value="BRL" selected>BRL</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
</select>

我想用这样的函数更改值(但行不通):

<a href="#" class="is-txt-green-light" id="invertConvert">Invert</a>

// JS
function invertCurrency() {
let sourceCurrency = $('#source_currency');
let targetCurrency = $('#target_currency');
const triggerInvert = $('#invertConvert');

triggerInvert.click((e) => {
e.preventDefault();
sourceCurrency.val(targetCurrency.val())
})
}

我该怎么做?谢谢!

最佳答案

如果您尝试像这样交换字段的值:

当用户点击反转按钮时,字段的值会被交换。

const triggerInvert = $('#invertConvert');

triggerInvert.click((e) => {
let sourceCurrency = $('#source_currency');
let sourceCurrency_val = sourceCurrency.val();

let targetCurrency = $('#target_currency');
let targetCurrency_val = targetCurrency.val();

e.preventDefault();
sourceCurrency.val(targetCurrency_val);
targetCurrency.val(sourceCurrency_val);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="source_currency">
<option value="GBP" selected>Pound Sterling</option>
<option value="USD">Dollar</option>
<option value="EUR">Euro</option>
</select>

<select id="target_currency">
<option value="GBP">Pound Sterling</option>
<option value="USD">Dollar</option>
<option value="EUR" selected>Euro</option>
</select>

<button id="invertConvert">
Convert
</button>

关于javascript - 如何反转两个输入选择之间的选项值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53859878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com