在1.4中通过jquery设置选择标签

在jquery 1.3.2中,以下工作:

 Red Purple  $('#c').val('Red'); 

并且它将选项更改为选项,并将RED作为其标签。 在jQuery 1.4中,这失败了。 如何在1.4中获得相同的结果? 这是1.3版本中的错误吗?

你必须这样做:

 $('option:contains("Red")', '#c')[0].selected = true 

编辑

@Tomalak

如果标签不相互排斥,则需要重写选择器:

 $.fn.labselect = function(str) { $('option', this).filter(function() { return $(this).text() == str; })[0].selected = true; return this; }; // Use it like this $('#c').labselect('Red'); 
 $('#c').val('Red'); 

不应该(imho)在jQuery 1.3中工作,因为“Red”不是值。 “325”是。 这是做什么的:

 $('#c').val("325"); 
 $('#c').val('325'); 

要么

 // earlier - define a text-equals selector jQuery.extend(jQuery.expr[":"], { "text-equals": function (a, i, m) { return (a.textContent||a.innerText||jQuery(a).text()||'')==m[3]; } }); // later - use it $red = $('#c option:text-equals(Red)'); $('#c').val($red.val()); 

自定义选择器是一种可能性。 例如,您也可以在filter()回调中执行完全相同的操作。

试试这段代码:

 $('#c').val("325");