我想使用jquery设置一个下拉框来显示通过querystring传递的所有内容。
如何将选中的属性添加到选项中,使"TEXT“值等于查询字符串中的某个参数?
$(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
});
};
});
发布于 2009-06-17 22:01:49
替换为:
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()
将自动选择具有该值的选项(如果有)。
发布于 2013-06-03 05:01:07
如果您的<option>
元素没有value
属性,那么您可以只使用.val
$selectElement.val("text_you're_looking_for")
但是,如果您的<option>
元素有value属性,或者将来可能有这样的属性,那么这就行不通了,因为只要有可能,.val
就会根据它的value
属性而不是文本内容来选择一个选项。如果选项有value
属性,没有内置的jQuery方法可以根据文本内容选择选项,所以我们必须用一个简单的插件自己添加一个:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
在将jQuery添加到页面后,只需在某个地方包含此插件,然后执行
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
选择选项。
该插件方法使用filter
仅挑选出与targetText匹配的option
,并使用.attr
或.prop
选择它,具体取决于jQuery版本(有关说明,请参阅.prop() vs .attr() )。
这里有一个JSFiddle,您可以使用它来尝试这个问题的所有三个答案,它表明这个问题是唯一可靠工作的:http://jsfiddle.net/3cLm5/1/
https://stackoverflow.com/questions/1009740
复制相似问题