简体   繁体   English

循环用尽的Javascript

[英]Javascript for loop running out of sequence

I have a confusing problem where a line of code in my function is running before a loop which is stated above it. 我有一个令人困惑的问题,函数中的一行代码在上面声明的循环之前运行。 In my HTML I have: 在我的HTML中,我有:

<textarea id="textBox"></textarea>
<button id="submitButton" onclick="parseData()">submit</button>
<div id="put"></div>

And my JS function is: 我的JS函数是:

function parseData() {
    var data = $("#textBox").val();
    var tab = /\t/;
    data = data.split(tab);
    $("#put").html($("#put").html() + "<table>");
    for (var i = 0; i < data.length; i++) {
        $("#put").html($("#put").html() + "<tr>"+data[i]+"</tr>");
    };
    $("#put").html($("#put").html() + "</table>");
    return;
};

The resulting html in $("#put") is this: $("#put")的结果html是这样的:

<table></table>
"SiO2 (%)Al2O3 (%)TiO2 (%)CaO2 (%)MgO2 (%) 8.21.25.31.51.8 45.32.52.60.210.5 65.23.48.70.0662.3 20.11.85.42.540.2 18.91.12.34.810.7"

I'm not sure why the final </table> is being placed before the for loop runs, and I'm not sure why the <tr> tags aren't being added within the for loop. 我不确定为什么要在for循环运行之前放置最后的</table> ,也不确定为什么不在for循环中添加<tr>标记。 Any pointers? 有指针吗?

jQuery automatically closes up tags upon insertion. jQuery在插入时自动关闭标签。 Try this. 尝试这个。

function parseData() {
    var data = $("#textBox").val();
    var tab = /\t/;
    var put_html = $("#put").html() + "<table>";
    data = data.split(tab);
    for (var i = 0; i < data.length; i++) {
        put_html += "<tr>"+data[i]+"</tr>";
    };
    put_html += '</table>';
    $("#put").html(put_html);
    return;
};

However, I notice that you aren't using <td> elements. 但是,我注意到您没有使用<td>元素。 You might want to look into fixing that too. 您可能也想解决此问题。

Every time you are adding content into the html() property rather than building the entire content and adding it. 每次将内容添加到html()属性中,而不是构建整个内容并将其添加时。

Since you are using jQuery you can bind the event using jQuery rather than adding that directly in the HTML 由于您使用的是jQuery,因此您可以使用jQuery绑定事件,而不是直接在HTML中添加事件

<textarea id="textBox"></textarea>
<button id="submitButton">submit</button>
<div id="put"></div>

$(function(){
    $("#submitButton").click(function(){
        parseData();
    });

    function parseData() {
        var data = $("#textBox").val();
        var tab = /\t/;
        data = data.split(tab);

        // Build your html
        $("#put").html('htmlstructure');
        return;
    }
});

Also you can look for something similar like concatenating the string in an array so that you don't create string isntances each time when you append, since strings are immutable. 另外,您还可以寻找类似的东西,例如将字符串串联在数组中,这样,由于字符串是不可变的,因此每次添加时都不会创建字符串等距。

Good example 好例子

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

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