使用JQuery选择一个下拉选项并启动OnChange功能

Use JQuery to select a dropdown option and fire the OnChange function

本文关键字:选项 启动 功能 OnChange 一个 选择 JQuery 使用      更新时间:2023-09-26

我有一个加载了下拉列表的页面,其中有一个带有id = "accounts"的选择下拉列表。当页面加载时,它已经在Account Orange页面上了。我想使用JQuery找到select id元素,然后强制它单击3选项,该选项应该是索引2。

<select id="accounts" onChange="changeAccount(this.form,this[this.selectedIndex].value)">
    <OPTION value="">Select One...</OPTION>
    <OPTION value="111">Account Red</OPTION>
    <OPTION value="222">Account Yellow</OPTION>
    <OPTION value="333">Account Blue</OPTION>
    <OPTION value="444" selected>Account Orange</OPTION>
</select>

像这样的东西有效:

jQuery('#accounts>option:eq(2)').prop('selected', true); 

目前,当页面加载时,它确实选择了正确的选项,尽管有"selected"标记,但它不会将其激发到OnChange功能以选择"Account Yellow",然后它会重新加载页面。这就是我希望它做的。

首先,最好通过值而不是索引来设置SELECT的值。因为您可能希望稍后(在源代码中或动态地)添加额外的OPTION,然后您的索引计数就会关闭

其次,我发现更好的做法是更改SELECT的值,而不是更改使其被选中的HTML属性/属性(例如,不设置/更改OPTIONselected属性,而是更改SELECT的值)。否则,您可能会得到多个selected OPTION,这些可能会起作用,但不是非常干净的编码。

第三,如果您使用OPTGROUP的,建议的>option:eq(2)选择器可能不起作用,因为OPTION不是SELECT的直接后代。

因此,我的建议是使用:jQuery('#accounts').val('222').change();

它选择正确的SELECT字段,然后将值设置为333,然后激发onchange事件(在这种情况下需要手动执行)。

$('#accounts>option:eq(2)').prop('selected', true).promise().then(function(){
     changeAccount(this.form,this[this.selectedIndex].value)
});

尝试以下操作:

jQuery('#accounts>option:eq(2)').prop('selected', true).closest('select').trigger('change');