简体   繁体   English

jQuery无法在JavaScript for循环中按预期工作

[英]jquery not working as expected in javascript for loop

I've encountered the problem of using jQuery inside the javascript for loop. 我遇到了在javascript for循环内使用jQuery的问题。 After more than 24 hours investigating I've decided to post the core of the problem. 经过24小时的调查,我决定发布问题的核心。 I've shrunk the code to the simple example: 我将代码缩减为简单的示例:

var a, i, j;
var n = $("div.kategorija_tekst").length;
document.write("n = " + n + "<br>");
for (i = 0; i < n; i++){
    a = $("div.kategorija_tekst").length;
    document.write("polje["+i+"]  = " + a +"<br>");
    for (j = 0; j < a; j++){
        document.write($("div.def_tekst").eq(j).height() + "px, ");
    }
}

I've got: 我有:

  • in Opera 12.14, Google Chome 24.0.1312.57 m, Safari 5.1.7., Firefox 18.0.2: 在Opera 12.14,Google Chome 24.0.1312.57 m,Safari 5.1.7。,Firefox 18.0.2中:

    n = 6, polje[0] = 0, polje[1] = 0, polje[2] = 0, polje[3] = 0, polje[4] = 0, polje[5] = 0, n = 6,polje [0] = 0,polje [1] = 0,polje [2] = 0,polje [3] = 0,polje [4] = 0,polje [5] = 0,

  • in IE8: 在IE8中:

    n = 6 n = 6

But it should be expected as: 但是应该预期为:

n = 6, polje[0] = 6, 28px, 28px, polje[1] = 6, 28px, 28px, polje[2] = 6, 28px, 28px, polje[3] = 6, 28px, 28px, polje[4] = 6, 28px, 28px, polje[5] = 6, 28px, 28px, n = 6,polje [0] = 6,28px,28px,polje [1] = 6,28px,28px,polje [2] = 6,28px,28px,polje [3] = 6,28px,28px,polje [ 4] = 6、28px,28px,polje [5] = 6、28px,28px,

Strange! 奇怪! Why has the a variable inside the for loop got zero value? 为什么有a变数内的循环获得零值? Why are the height() values (in the nested for loop) completely missing? 为什么height()值(在嵌套的for循环中)完全丢失? Why IE8 hasn't succeeded to write even this line(s)? 为什么IE8甚至没有成功编写此行?

("polje["+i+"]  = " + a + "<br>")

Any help would be greatly appreciated! 任何帮助将不胜感激!

document.write overwrites the documents content: document.write覆盖文档内容:

var a, i, j;
var n = $("div.kategorija_tekst").length; 
document.write("n = " + n + "<br>"); //document no longer has any elements
for (i = 0; i < n; i++){
    a = $("div.kategorija_tekst").length; // returns null, no such thing in document
    document.write("polje["+i+"]  = " + a +"<br>");
    for (j = 0; j < a; j++){
        document.write($("div.def_tekst").eq(j).height() + "px, ");
    }
}

You're overwriting the document content, so the next selector always returns null. 您正在覆盖文档内容,因此下一个选择器始终返回null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM