[英]How can I check if the value of a parameter passed to a javascript function is null?
I have the following javascript code: 我有以下javascript代码:
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
How can I make it so that the $targetSpan.removeClass(..).addClass
only work if the iconClass has a value when the function is called. 我如何才能使
$targetSpan.removeClass(..).addClass
仅在调用函数时iconClass具有值时才起作用。 I guess what I am confused about is do I check if it is defined or do I check if it has a length of 0 or more? 我想我感到困惑的是,我是否检查它是否已定义,或者我是否检查其长度是否为0或更长?
It would be best if you check for undefined
as well. 如果你检查
undefined
也是最好的。
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
if (typeof iconClass !== "undefined" && iconClass) {
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
}
Update Even though this is a very old answer, it is still relevant. 更新即使这是一个非常古老的答案,它仍然是相关的。 Therefore, i would like to update my answer with an improved one based on @jeremy's comment.
因此,我想根据@ jeremy的评论更新我的答案。
function changeButtonState(targetSelector, action, iconClass) {
var $target = $(targetSelector);
//this will not throw exception since iconClass is implicitly declared through the input parameter
if (iconClass) {
var $targetSpan = $(targetSelector + ' span');
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
}
This would allow the user (most likely you) to specify whether or not you want it to be active by either giving it a falsey value or a truthy value. 这将允许用户(很可能是您)通过赋予其假名值或真值来指定您是否希望它处于活动状态。 You may also want to check if it's undefined by using the
typeof
operator. 您可能还想通过使用
typeof
运算符来检查它是否未定义。
if(iconClass) {
$targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.