[英]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的所有option
或id
,則可以輸入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.