Solo per il gusto di farlo, ho rintracciato questo nel codice jQuery. La funzione .val() inizia attualmente alla riga 165 di attributes.js. Ecco la relativa sezione, con le mie annotazioni:
val: function(value) {
var hooks, ret, isFunction,
elem = this[0];
/// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
if (!arguments.length) {
/// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
if (elem) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
/// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
Così, potrete sia ottenere undefined
o ""
o null
- che valuta in falso in istruzioni if.
Forse si può fare una funzione di supporto se si utilizza lo stesso tipo di condizione molte volte. – mirrormx
se ($ (selector) .val()) dovrebbe funzionare. Se l'elemento non esiste restituirà 'indefinito' e se lo fa ma non ha lunghezza restituirà "" (che valuta come falso). – Benmj
@Benmj sarebbe "indefinito" anche come falso? Pensavo che non fosse così. – Dimskiy