内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我希望使用jQuery将下拉框设置为通过查询字符串传递的任何内容。
如何将所选属性添加到选项中,使“text”值等于查询字符串中的某个Param?
$(document).ready(function() { var cat = $.jqURL.get('category'); if (cat != null) { cat = $.URLDecode(cat); var $dd = $('#cbCategory'); var $options = $('option', $dd); $options.each(function() { if ($(this).text() == cat) $(this).select(); // This is where my problem is }); }; });
将其替换为:
var cat = $.jqURL.get('category'); var $dd = $('#cbCategory'); var $options = $('option', $dd); $options.each(function() { if ($(this).text() == cat) $(this).select(); // This is where my problem is });
在这方面:
$('#cbCategory').val(cat);
调用val()
在SELECT列表中,如果有此值,将自动选择该选项。
我仍然认为这种方法会更干净:
cat = $.URLDecode(cat); $('#cbCategory option:contains("' + cat + '")').prop('selected', true);
在这种情况下,你不需要使用each()
。虽然那时prop()
不存在,所以对于旧版本的jQuery使用attr()
你必须确定当你使用contains
因为你可以找到多个选项,以防字符串在cat
匹配与你要匹配的选项不同的子字符串。
那么你应该使用:
cat = $.URLDecode(cat); $('#cbCategory option') .filter(function(index) { return $(this).text() === cat; }) .prop('selected', true);