【发布时间】:2025-11-25 10:20:14
【问题描述】:
我正在尝试将几个中的第一个设置为选中
我有
<select name="id[21]" class="atributosSort">
<option value="107">1. Sin adaptadores de video (+$45)</option>
<option value="108">2. Mini Displayport to DVI (+$112)</option>
<option value="109">3. Mini Displayport to VGA</option>
</select>
我试过了
jQuery(".atributosSort")[0].selectedIndex = 0;
和
jQuery(".atributosSort option:first").attr('selected','selected');
两者都在 How to make first option of <select > selected with jQuery? 但是当我检查 DOM 时,没有任何属性被添加到任何
我正在使用 jQuery(),因为我处于 noConflict 模式。会不会是这个问题?
当我运行两次尝试以获取所选值时,脚本控制台中没有出现任何错误
另一件可能相关的事情是我正在用这个对选项进行排序
function sortDropDownListByText() {
// Loop for each select element on the page.
jQuery("select").each(function() {
// Keep track of the selected option.
var selectedValue = jQuery(this).val();
// Sort all the options by text. I could easily sort these by val.
jQuery(this).html(jQuery("option", jQuery(this)).sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
// Select one option.
//jQuery(this).val(selectedValue);
});
}
// Use jQuery via jQuery(...)
jQuery(document).ready(sortDropDownListByText);
我评论了 jQuery(this).val(selectedValue);因为我认为该行将某些选项设置为已选中,然后我无法覆盖它,但这没有区别。
有什么想法吗? 谢谢
【问题讨论】: