使用基于文本的 Jquery 选择选项
Select option using Jquery base on text
<select>
<option value="something else">James</option>
<option value="something else">John</option>
</select>
出于某种原因,我可以做$('select').val('something else')
因为 value 属性用于其他东西。为了避免弄乱当前的工作内容,如何根据文本值选择元素?说我已经得到了价值James
和John
.
$("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>
相关文章:
- 如何使用jQuery选择下拉列表的值
- 按照选项卡索引的顺序循环一个jQuery选择
- 使用Jquery选择或取消选择ListView中的所有复选框
- jQuery选择器无法正常工作
- 使用基于文本的 Jquery 选择选项
- 将jquery选择器转换为数组
- JavaScriptDOM正常工作时JQuery选择器不工作
- 在我的情况下,使用带有变量失败的 jquery 选择器
- 换行符插入jquery选择器
- 使用javascript"这个“;用于jquery选择器
- jQuery选择器缓存问题
- jQuery 选择器,所有跨度都在 DIV 内
- JQuery选择器:如果同级具有.class,则选择td
- jQuery选择器不识别任何动态创建的HTML输入函数
- 循环遍历元素jquery选择器
- jQuery选择器错误:无法识别的表达式
- 自定义jquery选择器属性未在模拟器中激发
- Jquery选择器为空,我应该使用哪个作用域
- jQuery选择JavaScript生成的元素
- Jquery选择菜单选项在页面刷新时失败