Jquery - 更改动态下拉列表选定元素

Mur*_*dvi 2 jquery element dynamic selected drop-down-menu

我有一个动态生成的Dropdown,我需要使用Jquery更改所选值.

<select class="txtfield country" id="ctl00_MainContentAreaPlaceHolder_personalInformation_country" name="ctl00$MainContentAreaPlaceHolder$personalInformation$country"> 
    <option value="FJ">FIDJI</option>
    <option value="FI">FINLANDE</option>
    <option value="FR" selected="selected">FRANCE METROPOLITAINE</option>
    <option value="GA">GABON</option>
</select>
Run Code Online (Sandbox Code Playgroud)

一种方法是使用下拉列表的整个ID(包括ctl00 ..):

$j("#ctl00_MainContentAreaPlaceHolder_DeliveryPersonalInformation_country option[value='FR']").attr('selected', 'selected'); 
Run Code Online (Sandbox Code Playgroud)

有没有办法使用CSS我可以找到元素并更改值,因为我不喜欢使用动态控件的ID?

编辑:

我忘了提到我在页面上有2个具有相同下拉名称的自定义控件.

所以自定义控件1生成:

<select class="txtfield ckgcountry" id="ctl00_MainContentAreaPlaceHolder_personalInformation_country" name="ctl00$MainContentAreaPlaceHolder$personalInformation$country">  ...
    <option value="ZW">ZIMBABWE</option>
</select>
Run Code Online (Sandbox Code Playgroud)

和客户控制2生成:

<select class="txtfield country" id="ctl00_MainContentAreaPlaceHolder_personalInformation_country" name="ctl00$MainContentAreaPlaceHolder$personalInformation$country">
    <option value="FJ">FIDJI</option>
    <option value="FI">FINLANDE</option>
    <option value="FR" selected="selected">FRANCE METROPOLITAINE</option>
    <option value="GA">GABON</option>
</select>
Run Code Online (Sandbox Code Playgroud)

所以使用代码它只更改它在DOM中找到的第一个名称的值,如何更改第二个名称的值...是否有办法使用CSS执行此操作?

a43*_*511 6

看起来你正在使用ASP.NET.

使用完整的ASP.NET控件ID(后渲染)确实不可靠,因为它可能会在某些时候发生变化.保证不会更改的ID的唯一部分是在ASP.NET Control的ID属性中定义的ID的最后一部分.

使用通配符选择器选择该项

// Unselect the currently selected item
$("select[id$='personalInformation_country'] option:selected").removeAttr("selected");

// Select the option at index 0
$("select[id$='personalInformation_country'] option:eq(0)").attr("selected","selected");
Run Code Online (Sandbox Code Playgroud)

要么

// Select the option with value FR
$("select[id$='personalInformation_country'] option[value='FR']").attr("selected","selected");
Run Code Online (Sandbox Code Playgroud)

$='personalInformation_country'会匹配所有ID的结尾与"personalInformation_country",这应该只有一个!