$(“select> option ”)不起作用

我需要用文本设置默认选择值,这是我的代码:

HTML:

 Firm Government Individual  

JavaScript的:

 $("#sel>option[text='Firm']).prop("selected", true); 

它不起作用,低于0:

 $("#sel>option[text='Firm']).length 

如果我使用属性值,它可以工作,但我需要在这里使用文本。

谢谢。

将元素的文本内容视为CSS选择器语法中的属性是不可能的。

但是,您可以编写一个filter来执行此操作:

 $('select option').filter(function() { return $(this).text() === "Firm"; }).whatever(); 

那是因为text不是CSS属性。

但是,您可以使用jQuery :contains selector

 $("select > option:contains('xxx')") 

您可以使用filter()根据其内部文本获取特定元素:

 $("#sel > option").filter(function() { return this.innerHTML == "Firm"; }).prop("selected", true);