如何检查一个选项是否被选中? [英] How to check if an option is selected?

查看:26
本文介绍了如何检查一个选项是否被选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('#mySelectBox option').each(function() {
    if ($(this).isChecked())
       alert('this option is selected');
     else
       alert('this is not');
});

显然,isChecked 不起作用.所以我的问题是这样做的正确方法是什么?谢谢.

Apparently, the isChecked doesn't work. SO my question is what is the proper way to do this? Thanks.

推荐答案

UPDATE

对所选选项更直接的 jQuery 方法是:

A more direct jQuery method to the option selected would be:

var selected_option = $('#mySelectBox option:selected');

回答问题 .is(':selected') 就是你要找的:

Answering the question .is(':selected') is what you are looking for:

$('#mySelectBox option').each(function() {
    if($(this).is(':selected')) ...

非 jQuery(可以说是最佳实践)的方法是:

The non jQuery (arguably best practice) way to do it would be:

$('#mySelectBox option').each(function() {
    if(this.selected) ...

不过,如果您只是在寻找选定的值,请尝试:

Although, if you are just looking for the selected value try:

$('#mySelectBox').val()

如果您要查找所选值的文本,请执行以下操作:

If you are looking for the selected value's text do:

$('#mySelectBox option').filter(':selected').text();

查看:http://api.jquery.com/selected-selector/

下次寻找重复的 SO 问题:

Next time look for duplicate SO questions:

获取当前选择的选项或者设置所选选项或者如何在 jQuery 中获取 $(this) 选择的选项?或者option[selected=true] 不起作用

这篇关于如何检查一个选项是否被选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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