javascript - 基于文本使用 Jquery 选择选项

标签 javascript jquery

<select>
  <option value="something else">James</option>
  <option value="something else">John</option>
</select>

出于某种原因,我可以执行 $('select').val('something else') 因为 value 属性用于其他内容。为了避免搞乱当前的工作,如何根据文本值选择元素?说我已经获得了值 JamesJohn

最佳答案

$("select option").filter(function() {
  return $(this).text() == 'John';
}).prop('selected', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="something else">James</option>
  <option value="something else">John</option>
</select>

使用.filter()

Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

关于javascript - 基于文本使用 Jquery 选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267611/

相关文章:

jquery - Node JS 排序数组通过 Handlebars 模板客户端传递

javascript - 光标 :pointer not working on input type file

javascript - 检查 Controller 中的按钮是否被点击

javascript - PHP 使用 AJAX 和 DataTables 发布数据

javascript - 谷歌应用程序脚本 : Automated reporting with Google Analytics

javascript - 无法触发链接上的点击事件

javascript - 如何使用 jquery 在相邻的 <td></td> 元素中添加/减去值

javascript - 为什么我不能在 javascript/JQuery 中获取图像的 naturalHeight/naturalWidth?

javascript - 为什么这个 AJAX 回调没有被调用?

javascript - 元素初始化中的 JQuery UI 变量