如何检查选项是否被选中?
如何检查选项是否被选中?
$('#mySelectBox option').each(function() { if ($(this).isChecked()) alert('this option is selected'); else alert('this is not'); });
显然,isChecked
不起作用。所以我的问题是什么是正确的方法?
谢谢。
admin 更改状态以发布 2023年5月21日
您可以通过以下方式获取选择的选项:
$('#mySelectBox option:selected')...
但是,如果您想要迭代所有选项,请使用this.selected
而不是不存在的this.isChecked
:
$('#mySelectBox option').each(function() { if (this.selected) alert('this option is selected'); else alert('this is not'); });
更新:
您得到了很多建议使用以下内容:
$(this).is(':selected')
,那么为什么不使用本机DOM元素方法,可以更快,更容易地使用this.selected
来完成它?
在jQuery
标签信息中阅读了解您的DOM属性和函数
更新
一种更直接的jQuery方法来选取选项是:
var selected_option = $('#mySelectBox option:selected');
回答问题 .is(':selected')
是你要找的:
$('#mySelectBox option').each(function() { if($(this).is(':selected')) ...
非jQuery(可能是最佳实践)的方法是:
$('#mySelectBox option').each(function() { if(this.selected) ...
虽然,如果只是想找到选定的值,试试:
$('#mySelectBox').val()
如果想找到选定值的文本,则使用:
$('#mySelectBox option').filter(':selected').text();
查看:http://api.jquery.com/selected-selector/
下次先查找重复的SO问题:
获取当前选定选项
或者
设置选定选项
或者
如何在jQuery中获取$(this)选定选项?
或者
选项[selected=true]不起作用