문제

I am a complete newbie in programming so be easy on me.

I want to print an array object into a table in HTML using getElementByID.

 <script>

       var ram = ["8GB", "3GB"];
       var storage = ["500GB" , "120GB"];

       document.getElementById("mac.r").innerHTML = ram[0];
       document.getElementById("mac.s").innerHTML = storage[0];

</script>

And I want to print it in a table

<table width="600" border="6" cellpadding="5px">
  <tr>
    <td>&nbsp; Ram</td>
    <td>&nbsp; Storage</td>
  </tr>
  <tr>
    <td id="mac.r"></td>
    <td id="mac.s"></td>
  </tr>
</table>

I use a macbook and google chrome.

도움이 되었습니까?

해결책

If you must keep your script inline place it at the bottom of your page. See below, you can view the fiddle here

Once the element exists that you need to populate, you then loop the the data you need and fill the related element with your data.

<html>
    <body>
        <table width="600" border="6" cellpadding="5px">
            <tr>
                <td>&nbsp; Ram</td>
                <td>&nbsp; Storage</td>
            </tr>
            <tr>
                <td id="mac.r"></td>
                <td id="mac.s"></td>
            </tr>
        </table>
        <script>
            (function() {
                var ram = ["8GB", "3GB"];
                var storage = ["500GB", "120GB"];
                var macR = document.getElementById('mac.r');
                var macS = document.getElementById('mac.s');

                for(var i = 0; i < ram.length; i++){
                    if (macR !== null) macR.innerHTML = macR.innerHTML + ram[i] + "<br>";
                }
                for(var i = 0; i < ram.length; i++){
                    if (macS !== null) macS.innerHTML = macS.innerHTML + storage[i] + "<br>";
                }
            })();
        </script>
    </body>
</html>

다른 팁

One simple approach is to use the array's build-in "forEach" method:

var ram = ["8GB", "3GB"],
    storage = ["500GB" , "120GB"];

ram.forEach(function(element, index, array){
    document.getElementById("mac.r").innerHTML += element;
});

storage.forEach(function(element, index, array){
    document.getElementById("mac.s").innerHTML += element;
});

See it here: http://jsfiddle.net/S3CY4/

Be aware though its mostly supported in modern browsers and it may not be the most performant approach.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top