select选项与cheerio(jQuery)的文字
我试图从select下拉列表中select带有cheerio
的HTML元素的text()
属性的cheerio
。 到目前为止,我正在做的是,我试图将attr
设置为选定的匹配,具有特定文本的元素。
这就是我想要的:
$('#ddl_city option[text="testing"]').attr('selected', 'selected');
当我这样做时,我没有得到任何HTML的变化。 在完成这个操作之后,我在控制台上打印了html文档,但是我没有看到这个选项已经改变为我正在select的那个。 任何想法为什么不工作或另一种解决方法?
您可以使用:contains
filter根据文本获取特定的option
元素,并将select
元素的值设置为它的值:
$('#s1').val($("#s1 option:contains('Val B')").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="s1"> <option value="a">Val A</option> <option value="b">Val B</option> </select>
你可以试试这个:
$('#ddl_city option'). filter(function () { return $(this).text() == 'testing'; }). attr('selected', true);
感谢Godsbest在jQuery论坛的这篇文章中的回答。