问题
I have a site which used jquery 1.x.... Now, I have started using jquery 3.x in this site..... to solve any migration issues, I have installed JQMigrate.
One of the messages it shows in console window is "JQMIGRATE: jQuery.fn.offset() requires an element connected to a document".
I am not sure how I can solve it. The only thing that is said as a "solution" is: "Do not attempt to get or set the offset information of invalid input."
That is obvious, but what does it mean in practice? if I have, for example,
var parentOffset = $offsetParent.offset();
Should I write that line something like this?
var parentOffset = $offsetParent ? $offsetParent.offset() : 0;
Is it really necessary since I know that $offsetParent is always a valid input.
Regards Jaime
回答1:
I just came across this same line of code.
The problem here is that the $offsetParent
element is not part of the document
.
Instead of checking $offsetParent.length
we want to make sure this element is actually part of the document
// As of jQuery 3.0, .offset() only works for elements that are currently
// in the document. In earlier versions, this would return the value below
// but in jQuery 3.0 this throws an error.
var parentOffset = {top: 0, left: 0};
// If the element is in the document we are safe to use .offset()
if(document.body.contains($offsetParent[0])) {
parentOffset = $offsetParent.offset();
}
See https://github.com/jquery/jquery-migrate/blob/master/warnings.md#jqmigrate-jqueryfnoffset-requires-an-element-connected-to-a-document for more information on this change.
回答2:
if(jQueryObject)
will always be truthy even if a match doesn't exist for the selector or method used to obtain the element
Check it's length instead
var parentOffset = $offsetParent.length ? $offsetParent.offset() : 0;
来源:https://stackoverflow.com/questions/51681100/jqmigrate-jquery-fn-offset-requires-an-element-connected-to-a-document