gpt4 book ai didi

javascript - 同步 2 个选择框

转载 作者:行者123 更新时间:2023-11-28 08:58:26 25 4
gpt4 key购买 nike

我有两个选择框:

<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>

当一个框更改时,另一个框需要更改为相应的索引(即如果“县”中选择 Dixie,则“站点”中应选择 Florahome)。我使用 jQuery 的尝试如下,但似乎不起作用。

$('select#countyselect').change(function() {
var countySelector = $('select#countyselect').attr("selectedIndex");
$('select#siteselect').attr('selectedIndex', countySelector);
});
$('select#siteselect').change(function() {
var siteSelector = $('select#siteselect').attr("selectedIndex");
$('select#countyselect').attr('selectedIndex', siteSelector);
});

有什么想法吗?

最佳答案

您需要的是 prop,而不是 attr。像这样的东西:

function matchUp(selected, toselect)
{
var idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}


$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);

$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);

function matchUp(selected, toselect)
{
const idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}


$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);

$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>

关于javascript - 同步 2 个选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18113307/

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