开发者

Check if the window, and if so, change to document in jQuery Plugin

I have a plugin, jKey, and people kept reporting IE bugs that it didnt work. The bug isn't with my script, or jQuery, but rather IE doesn't support window keypresses. I want to "auto-correct" this by checking if the $(window) was selected (which i did below by check, if "this" has a parentNode) and if it was i want to switch this to document.

I'm having no luck tho. I keep getting:

Uncaught ReferenceError: Invalid left-hand side in assignment

I've tried:

if($(this)[0].parentNode == undefined){
    $(this) = $(document);
}

And:

if($(this)[0].parentNode == undefined){
    this = document;
}

Any ideas? Also, if you have a better way of checking for the window please let me 开发者_如何学运维know!


  • $ is a function. $(this) is a function invocation. You cannot assign a value to a function invocation.
  • this never directly assignable.
  • Are you really jQuery-ifying this and then immediately unwrapping it?

    $(this)[0].parentNode
    // is exactly equivalent to
    this.parentNode
    

Also, if you have a better way of checking for the window please let me know!

In the plugin, alias this to a keyword that you can assign. A frequent choice is self:

// plugin entry point
var self = this;

// use self instead of this throughout the rest of the plugin

Now you actually can change the "scope:"

if (!this.parentNode) {
    self = document;
}

your snippet seems to convert all selections to document? not just window? so $('input') is converted to document

Oh, right, you're talking about a jQuery plugin. this is probably already a jQuery object, in which case this.parentNode would always be a falsy value. You can either unwrap it:

if (!this[0].parentNode) {
    self = $(document);
}

or use

if (this.first().parent().length) {
    self = $(document);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜