jQuery - 通过文本描述设置选择控件的选定值 [英] jQuery - setting the selected value of a select control via its text description

查看:18
本文介绍了jQuery - 通过文本描述设置选择控件的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择控件,在一个 javascript 变量中我有一个文本字符串.

I have a select control, and in a javascript variable I have a text string.

使用 jQuery,我想将选择控件的选定元素设置为具有我拥有的文本描述的项目(而不是我没有的值).

Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).

我知道按值设置它非常简单.例如

I know setting it by value is pretty trivial. e.g.

$("#my-select").val(myVal);

但是我对通过文本描述来做这件事有点难.我想一定有办法从文本描述中获取价值,但我的大脑在周五下午太忙了,无法计算出来.

But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.

推荐答案

按描述选择 jQuery v1.6+

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).prop('selected', true);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).attr('selected', true);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

请注意,虽然此方法适用于 1.6 以上但低于 1.9 的版本,但自 1.6 以来已被弃用.它在 jQuery 1.9+ 中不起作用.

Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.

val() 应该处理这两种情况.

val() should handle both cases.

$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

这篇关于jQuery - 通过文本描述设置选择控件的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆