繁体   English   中英

通过文本选择带有cheerio(jquery)的选项

[英]Select option with cheerio (jquery) by text

我正在尝试使用带有cheerio的HTML元素的text()属性从选择下拉列表中选择一个选项。 到目前为止,我正在尝试将attr设置为选定的匹配项,即具有特定文本的元素。

这是我正在尝试的:

$('#ddl_city option[text="testing"]').attr('selected', 'selected');

这样做时,我在html上没有任何更改。 完成此操作后,我在控制台上打印了html文档,但没有看到该选项已更改为我选择的选项。 知道为什么不起作用或其他解决方法吗?

您可以尝试以下方法:

$('#ddl_city option').
    filter(function () { return $(this).text() == 'testing'; }).
    attr('selected', true);

学分Godsbest在回答这个职位上的jQuery的论坛。

您可以使用:contains过滤器根据文本获取特定的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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM