我正在驗證一些字段,並檢查一個選擇元素的長度是否大於0.我得到的錯誤「'長'是空或不是一個對象」,因爲ID $ = SelectResult是一個列表框,可以沒有值和因此返回null和var val = $(this).val();不喜歡那樣。如果變量爲null,則用jQuery將該值設置爲0?
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
var controlsPassed = 0;
$("input[id$=UserField_hiddenSpanData],input[title=Title],select[id$=SelectResult]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 3)
case 'Milestone Action':
var controlsPassed = 0;
$("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic
Objective],select[title=Strategic Priority]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 7)
case 'Performance Measure':
var controlsPassed = 0;
$("select[title=Strategic Objective],input[title=Title],select[id$=SelectResult],select[title=Strategic Priority]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 4)
case 'Strategic Priority':
var controlsPassed = 0;
$("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic
Objective]").each(function(){
//var ResponsibleBusiness = $("select[id$=SelectResult]").val();
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 6)
}
}
function PreSaveItem() {
return checkControls()
}
當有些東西不存在,它是'undefined',而不是'null'。唯一的例外是,如果某個具有所提供的ID的節點不存在,則'document.getElementById'返回'null'。 – 2010-08-20 01:08:56