[英]Google Chrome crashes, doesn't recognize a variable as the name of a function
the following code works perfect of Firefox but crashes on Chrome, with the following error: Uncaught TypeError: Property 'pos' of object [object Object] is not a function 以下代码在Firefox上运行完美,但在Chrome上崩溃,并出现以下错误:未捕获的TypeError:对象[object Object]的属性'pos'不是函数
Here is the code, with comments: 这是带有注释的代码:
var CantidadMenu = $('div[class^=container_menu_]').length;
var position = $("#menu_unidades").position();
var IzAdd = 0;
var w = $("#menu_unidades").width();
var h = $("#menu_unidades").height();
for (i=0;i<CantidadMenu;i++){
var pos = 'pos'+(i+1); //I create a variable that will hold a string like: pos1,pos2...
IzAdd = IzAdd+25;
function pos(div){ //on this line I use the variable I created, which crashes on Chrome
var estilo1 = $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
return estilo1;
}
pos('.container_menu_'+(i+1));
$('.container_menu_'+(i+1)).css({'z-index':297+i,'width':w,'height':h});
}
Here you define a function named pos: 在这里,您定义了一个名为pos的函数:
function pos(div){ //on this line I use the variable I created, which crashes on Chrome
var estilo1 = $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
return estilo1;
}
console.log(pos) // function ....
Here you overwrite it with a string: 在这里,您使用字符串覆盖它:
var pos = 'pos'+(i+1);
console.log(pos) // string....
You should name either the function or the string to something else. 您应该将函数或字符串命名为其他名称。
PS: I know that in your code the order is reversed, but function declarations are hoisted to the top of the scope, so the JS interpreter "sees" them in the order i wrote them in: first function, then the string. PS:我知道在您的代码中顺序相反,但是函数声明被提升到作用域的顶部,因此JS解释器按照我在其中编写的顺序“看到”它们:第一个函数,然后是字符串。
PSS: The crash is actually on this line: PSS:崩溃实际上是在此行上:
pos('.container_menu_'+(i+1));
function pos(div)
is the same as var pos = function(div)...
(except the former is defined at the parse-time, and the latter at the run-time, but that's irrelevant for your code), so if you expected by defining that pos = 'pos1';
function pos(div)
与var pos = function(div)...
(除了前者是在解析时定义的,后者是在运行时定义的,但这与您的代码无关),因此如果您期望通过定义pos = 'pos1';
, for example, you'd get function pos(div)
to become function pos1(div)
, it won't . ,例如,您将使
function pos(div)
function pos1(div)
成为function pos1(div)
, 而不会 。
It will just overwrite the pos
variable, and it will no longer be a string, but a function. 它只会覆盖
pos
变量,它将不再是字符串,而是一个函数。
To fix your code, write a single function at the top of your code, outside of the for loop, add another parameter to it ( IzAdd
) and make sure you fix the function calls appropriately. 要修复您的代码,请在代码顶部的for循环外编写一个函数,向其中添加另一个参数(
IzAdd
),并确保正确修复了函数调用。
The function should look something like this: 该函数应如下所示:
function pos(div, IzAdd){
return $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.