1

我有两个选择框:

<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);
});

有任何想法吗?

4

1 回答 1

1

你想要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>

于 2013-08-07T20:43:19.937 回答