繁体   English   中英

typeof不适用于未定义的类型

[英]typeof not working for undefined type

基本上我正在检查我是否得到一些选定的ID,然后使用该选定的值,否则使用来自不同属性的值,有时它发生时没有选定的项,所以我不确定,但是以下代码不能解决我的问题

var user_role = $('#user_role option:selected').attr('id');
        if (typeof user_role === 'undefined') {
            alert(intval(jQuery('#selected_role').val()));
            user_role = jQuery('#selected_role').val();
        }

我也尝试过

var user_role = $('#user_role option:selected').attr('id');
        if (typeof user_role === undefined) {
            alert(intval(jQuery('#selected_role').val()));
            user_role = jQuery('#selected_role').val();
        }

编辑:对于那些问我要检查if(!user_role)的人,我已经检查过了,它无法正常工作。以上两种方式中的任何一种我都不会进入我的if条件。

undefined检测效果很好。 “问题”是,如果未选择任何内容,则option:selected返回第一个选项,因此typeof .attr('id')永远不会是"undefined"

 var user_role = $('#user_role option:selected').attr('id'); document.body.innerHTML += user_role; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="user_role"> <option id="opt1">Opt1</option> <option id="opt2">Opt3</option> <option id="opt3">Opt3</option> </select> 

(如果省略了options的所有optionid ,则可以输入if 。)

检查某物是否为jQuery对象的最佳方法(这样就不会出现未定义的错误)是这样的:

var user_role = $('#user_role option:selected').attr('id');
if (!user_role) {
     alert(intval(jQuery('#selected_role').val()));
     user_role = intval(jQuery('#selected_role').val());
}

undefined是一个对象(不是类型),请尝试以下操作:

if (user_role === undefined)
{}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM