[英]typeof not working for undefined type
basically i am checking if i get some selected id then use that selected value, otherwise use value from different attribute, at times it happens there is no selected Item so i get undefined, but following code dont solve my problem 基本上我正在检查我是否得到一些选定的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();
}
i have also tried 我也尝试过
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();
}
EDIT: For those asking me to check if(!user_role ) i have already check it and it dont work In either of the above way i am not getting into my if condition. 编辑:对于那些问我要检查if(!user_role)的人,我已经检查过了,它无法正常工作。以上两种方式中的任何一种我都不会进入我的if条件。
Your undefined
detection works fine. 您
undefined
检测效果很好。 The "problem" is, that if nothing is selected, option:selected
returns the first option, hence typeof .attr('id')
is never "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>
(If you omitted all the option
s or id
s of options, you could enter the if
.) (如果省略了options的所有
option
或id
,则可以输入if
。)
The best way to check if something is a jQuery object (so you don't get any undefined errors) is like this: 检查某物是否为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 is an object(not a type) try this: undefined是一个对象(不是类型),请尝试以下操作:
if (user_role === undefined)
{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.