使用基于文本的 Jquery 选择选项

Select option using Jquery base on text

本文关键字:Jquery 选择 选项 文本 于文本      更新时间:2023-09-26
<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((

说明:将匹配的元素集减少为与选择器匹配或通过函数测试的元素集。

您可以使用

以下内容

 $("#yourdropdownid option:selected").text();

这将为您提供文本

$('select').find('option[value="something else"]').prop("selected", true)

尝试使用$("select :selected").text();

使用contains通过这样的文本选择选项。

小提琴演示

堆栈示例:

$(function() {
  var text = "John";
  $("select option:contains(" + text + ")").attr('selected', 'selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select>
  <option value="something else">James</option>
  <option value="something else">John</option>
</select>

var selectText = function(elem, text) {
  if (elem && text) {
    elem.find('option').each(function() {
      var that = $(this);
      if (that.text() == text) {
        that.attr('selected', 'selected');
      }
    });
  }
}
selectText($('#target'), 'John');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="target">
<option value="something else">James</option>
<option value="something else">John</option>
</select>