检查是否设置了$(this)

时间:2012-05-14 11:58:23

标签: jquery jquery-selectors

我有一个功能,说:

function some_name( that ) {
// do something here
}

此函数在2个地方被调用。地点1在document.ready处,地点2在点击按钮时。

所以:

// document.ready
function some_name();

...

// button click
function some_name( $(this) );

现在回到函数本身,如何检查是否已设置that

2 个答案:

答案 0 :(得分:2)

一种选择是使用typeof

function some_name(that) {
    if (typeof that != "undefined") {
        // do smth with that
    } else {
        // do smth without that
    }
}

另一种选择是使用arguments

function some_name(that) {
    if (arguments.length) {
        // do smth with that
    } else {
        // do smth without that
    }
}

如果您还需要检查网页上是否存在元素$(this),则可以使用length

if (that.length) {
    // element exists
} else {
    // element does not exist
}

答案 1 :(得分:1)

function some_name(that) {
    if (that != undefined) {
        alert('that is good!');
    }
}