Domanda

Got a problem here. Been searching on Google and the website for a few hours, but can't find the solution.

The problem

I've got 3 variables, which store classes, sections or ids. I bundle them together like below:

var clickedElement = '$("' + headParentID + parentClass + ' ' + thisNodeName + '")';

The value of clickedElement is the following:

$("#navigation .logo img")

The next step is to find the x coordinates of this 'element' using the following code:

var x = clickedElement.offset().left;

And here comes the problem. I'm getting the following error in the console logs:

Uncaught TypeError: Object $("#navigation .logo.six.columns img") has no method 'offset'

But when I use the output of clickedElement and put it in the code like the example below, it does give me the x coordinates..

var x = $("#navigation .logo img").offset().left;

Any jQuery/Javascript hero around that can solve this mystery? It would mean a lot!

Thanks!

È stato utile?

Soluzione

What you are doing here is not actually generating a jQuery object. You are actually just concatenating a string:

var clickedElement = '$("' + headParentID + parentClass + ' ' + thisNodeName + '")';
// result (note the quotes surrounding the object: 
// clickedElement = '$("#navigation .logo img")'

What you want to do is something like this:

var clickedElement = $( headParentID + parentClass + ' ' + thisNodeName );
// result: clickedElement = $("#navigation .logo img")

The error you are getting is basically saying that a string object does not have the offset() method.

Altri suggerimenti

You are actually searching for a method .offset() over a string.

Try,

var clickedElement = $(headParentID + parentClass + " " + thisNodeName);
var x = clickedElement.offset().left;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top