我有以下javascript代码:

    function changeButtonState(targetSelector, action, iconClass) {
        var $target = $(targetSelector);
        var $targetSpan = $(targetSelector + ' span');
        $targetSpan.removeClass('sprite-blank').addClass(iconClass);

我该如何做才能使$targetSpan.removeClass(..).addClass仅在iconClass具有
调用函数时的值。我想我很困惑的是我是否检查它是否已定义
还是检查长度是否为0或更大?

最佳答案

最好同时检查undefined

function changeButtonState(targetSelector, action, iconClass) {
    var $target = $(targetSelector);
    if (typeof iconClass !== "undefined" && iconClass) {
        var $targetSpan = $(targetSelector + ' span');
        $targetSpan.removeClass('sprite-blank').addClass(iconClass);
    }
}​

更新
即使这是一个非常古老的答案,它仍然是有意义的。因此,我想根据@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);
    }
}​

10-04 19:41