简体   繁体   English

jQuery下拉列表按文本选择选项

[英]JQuery Drop Down List select option by text

I have a select statement and a bunch of options. 我有一条选择语句和很多选择。 How do I choose an option by text using jQuery and at the same time deselect the default one, I am using selenium webdriver with python but I want to be able to do this in jQuery, because it seems like a basic thing I should know in jQuery and I would be able to translate it to python selenium myself once I understand how the jQuery works. 如何使用jQuery通过文本选择选项,同时取消选择默认选项,我将Selenium Webdriver与python一起使用,但我希望能够在jQuery中做到这一点,因为这似乎是我应该了解的基本知识jQuery,一旦我了解了jQuery的工作原理,便可以将其自己翻译为python硒。

<select id="DropDownList">
  <option selected="selected" value="2"> Test1</option> 
  <option value="8"> Test2 </option> 
</select>

This is close to what I want. 这接近我想要的。 I have tried multiple functions and selections, but they result in either an empty array, or when I loop them give me all a list of undefined, or a list of every possible attribute they can have. 我尝试了多种功能和选择,但是它们导致一个空数组,或者当我循环它们时,给我所有未定义的列表,或者它们可能具有的所有可能属性的列表。 The site is also designed using jQuery mobile if that makes any big difference in selection. 如果选择方面有很大不同,该网站还使用jQuery mobile设计。 Please and thank you. 谢谢,麻烦您了。

You mean select by text? 您是说按文字选择? This should work: 这应该工作:

$("#DropDownList option:contains(" + 'Test2' + ")").attr('selected', true);

Update: to deselect previously selected value, you can do: 更新:要取消选择先前选择的值,您可以执行以下操作:

$("#DropDownList :selected").attr('selected', false);

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

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