tinfanide Posted October 19, 2016 Share Posted October 19, 2016 var xmlhttp; var Staff, obj; var url = "staff.json"; function init() { xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP") ? new ActiveXObject("Msxml2.XMLHTTP") : null ; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { Staff = JSON.parse(this.responseText); var table = document.createElement("table"); document.body.appendChild(table); obj = Staff.Staff[0]; for (var y in obj) { var header_row = document.createElement("th"); var column = document.createElement("td"); var data = document.createTextNode(y); column.appendChild(data); header_row.appendChild(column); table.appendChild(header_row); } for(var x=0; x<Staff.Staff.length; x++) { obj = Staff.Staff[x]; if (x%2 == 0) { var row = document.createElement("tr"); row.setAttribute("class","even"); // function? for (var y in obj) { var column = document.createElement("td"); var data = document.createTextNode(obj[y]); column.appendChild(data); row.appendChild(column); table.appendChild(row); } } else { var row = document.createElement("tr"); // function? for (var y in obj) { var column = document.createElement("td"); var data = document.createTextNode(obj[y]); column.appendChild(data); row.appendChild(column); table.appendChild(row); } } } } }; xmlhttp.open("GET",url,true); xmlhttp.send(); } window.onload = init; Since the codes below "// function?" are repeated (either the row to be created in the JavaScript is odd or even), how can I write the same codes into ONE function to be shared and used in different places? Thanks for any help! Link to comment Share on other sites More sharing options...
dsonesuk Posted October 19, 2016 Share Posted October 19, 2016 I suspect you would require coding from for loop and then pass value arguments of row, table and obj with function. Link to comment Share on other sites More sharing options...
Ingolme Posted October 19, 2016 Share Posted October 19, 2016 You don't need a function, just take the invariants out of the if() statement: // Before the ondition var row = document.createElement("tr"); // Check the condition if (x%2 == 0) { row.setAttribute("class","even"); } // After the condition for (var y in obj) { var column = document.createElement("td"); var data = document.createTextNode(obj[y]); column.appendChild(data); row.appendChild(column); table.appendChild(row); } 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now