I have a very odd problem with javascript. My code is rather long so here is an example of the structure and the problem:
var x = new function f() {
this.id = "";
}
function g(obj) {
if (x.id == "") {
...
obj.firstChild.setAttribute("onclick", "javascript:o();");
...
x.id = obj.id;
} else if (x.id != obj.id) {
...
x.id = "";
g(obj);
}
}
function o() {...
if (something == something) {
...
} else {
...
x.id = ""; // if-statement of the g() function is called here?
}
}
As you can see, the if-statement of the g() function is for some reason called or re-run upon x.id being changed. I simply cannot understand this, because they are not in the same scope, and changing a variable should under no circumstances trigger anything?
Any help would be greatly appreciated.
If the code really is as you show it, that line of code will not generate a function call. The line is simply an assignment to the
idproperty ofx. The only way a function call could be triggered by your assigning to theidproperty ofxwould be if you were using a browser that supported property accessors (getters and setters), which is very unlikely (and there’s nothing in your code doing so).Something else would appear to be calling
gin a loop of some kind, and so your changing the value makes the next call togsee the change. As Jonathon pointed out in his comment on the question, this could be something you’ve set up withsetTimeout, orsetInterval, or in an even handler (on mouse move, for instance), etc., but it’s nothing in the quoted code.Possibly off-topic:
You have this line of code at the outset:
That code uses a “named function expression,” which should be valid but causes problems in some implemenations (IE, for instance). Split it up to get the desired result reliably cross-browser:
Off-topic:
You don’t use the
javascript:pseudo-protocol except on attributes that take a URI (likehrefonaelements). Theonclickattribute does not take a URI, it takes JavaScript code, so change:to
But, better yet, assign the handler directly:
…or even consider using
addEventListeneror its IE-counterpartattachEventinstead.