开发者

determine selector validity

I have a function like this:

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue;

    if ($(value).size() > 0)
        return $(value).val();

    return value;
};

value can be a function, a "value", or a jquery selector. My problem is how do I determine that the selector is valid (finds a control).

for example, when value equals 56.87 $(value).size() > 0 evaluates to true. I want it to be false. Even if something like #invalidcontrolid was pas开发者_开发知识库sed in, if it doesn't actually exist on the page, I want to get false back so I can return the value. Any ideas?


.size() is just a wrapper method for .length property. So this should (and does) work:

http://www.jsfiddle.net/EawgE/

You should check within your parseValue method if value actually is a number. If so, just return false or whatever but don't pass it into the jQuery constructor.

if( typeof value === 'number' ) {}

or

if( $.type(value) === 'number' ) {}

Example:

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if ( $.type(value) === 'number' )
        return value; // ?

    if ( $.type(value) === 'string' && $(value).length )
        return $(value).val();

    return defaultValue;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜