使用 JQuery,如何引用同级的第一个选项

Using JQuery, how do I reference the first-option of a sibling?

本文关键字:选项 第一个 引用 JQuery 何引用 使用      更新时间:2023-09-26

我有兄弟姐妹 SELECT 菜单元素,这样......

<select name="country1" class="country">...</select>
<select name="state1" class="state">...</select>

名称将更改(例如"国家/地区 1"..."countryn"),但与元素关联的类(例如"country"和"state")不会。 在我的Javascript中,我想重写这一行...

var firstOption = $("#state option:first-child");

鉴于我有一个国家元素 $(countryElt),我想说,存储 $(countryElt) 的兄弟姐妹".state"元素的第一个选项。 我怎么写?

$('.state option:first')
  .parent()
  .siblings('.country')
  .find('option:first');

嗨,戴夫,根据您的评论,我们最好在第二个选择中添加一个 ID,如下所示。

<select name="state1" class="state" id="state">...</select>. 

所以代码将更改为

$('#state option:first')
  .parent()
  .siblings('.country')
  .find('option:first');
您可以使用

parent()siblings(),如下所示:

var stateFirstOption = $("#state option:first");
var countryFirstOption = $stateFirstOption.parent().siblings('.country').find('option:first');

你可以做:

$(countryElt).next("select.state option:first")