开发者

How to know if you have a jQuery object

Two questions really...

Firstly, which is the better coding style when writing jQuery functions which take object params, should the function take a jQuery object or is it better to pass a standard JavaScript object and have the function itself do the wrapping? I guess I'm just asking if there is a standard here, since 开发者_运维知识库it might not always be obvious to someone who wants to call the function.

And secondly, how do you test if an object is a jQuery object? Ideally it would be nice if the function could take either, so...

function(obj) {
    var $obj;
    if (isJQuery(obj)) {
        $obj = obj;
    }
    else {
        $obj = $(obj);
    }
    // ....
}

or do you even need to do this? will $(obj) simply return if the object is already a jQuery object, so you can always attempt to wrap and it doesn't matter?


You can test for the .jquery property (which is on the prototype of jQuery objects), like this:

function(obj) {
  var $obj = obj.jquery ? obj : $(obj);
}

This is what jQuery core does internally as well.


Update: My ticket filed as a result of this question was completed, you can now find the .jquery property in the official API documentation.


Edit: as @T.J. points out in comments this isn't currently in the official API, however it's been around since jQuery 1.0 and I'm pretty sure it isn't going anywhere. All the same based on comment discussions (thanks T.J.), I submitted an enhancement ticket to hopefully get this added to the API documentation, you can track its progress here: http://bugs.jquery.com/ticket/7200


I would think something along these lines:

    if (obj instanceof jQuery) {
        $obj = obj;
    }
    else {
        $obj = $(obj);
    }

will $(obj) simply return if the object is already a jQuery object, so you can always attempt to wrap and it doesn't matter?

Well, it returns a clone of the jQuery object that you pass (see the documentation). This may probably result in unintended behavior.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜