简体   繁体   中英

simple javascript appendChild doesn't work

I'm new to web programming. I have tried to draw a table row with JavaScript but it's not working and I don't' know why.

here's the code

<div id="gameDiv"> </div>
<script type="text/javascript">
    public function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'
        for (j=0; j<8; j++) {
            var text = document.createTextNode(c++);
            var cell = startRow.insertCell(j);
            cell.appendChild(text);
        }
        document.getElementById("gameDiv").appendChild(table);
    }
    $(document).ready(function() {
        drawGame();
    };
</script>

The problem is the fact you use public . Javascript doesn't have public or private , so putting that in front of your function declaration will cause errors. If you open up your console, you'll see an error like:

SyntaxError: Unexpected token function

So to fix this, simply remove the private modifier from your code.

Also, you seem to be missing a closing parenthesis at the end of your code. Instead, you should use this:

$(document).ready(function() {
    drawGame();
});

but that code could also be written much shorter:

$(drawGame);

Well, you're getting an error because I think you might be getting your languages mixed up, there's no need to declare a function as public in javascript, it will give you an error.

The drawGame function can just be:

    function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'
        for(j=0; j<8; j++){
            var text = document.createTextNode(c++);
            var cell = startRow.insertCell(j);

            cell.appendChild(text);

        }
}

这是一种工作变体http://jsbin.com/hisewamu/4/edit ,“ $”概念是jquery的一部分,您应该包括

This should get rid of that NaN (Not a Number) nonsense.

<script>
        function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'.charCodeAt()
        for(j=0; j<8; j++){
            var text = document.createTextNode(String.fromCharCode(c++));
            var cell = startRow.insertCell(j);

            cell.appendChild(text);

        }
    document.getElementById("gameDiv").appendChild(table);

    }

    $(document).ready(function() {
    drawGame();

    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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