Jump to content
tinfanide

JavaScript Function & Parameters

Recommended Posts

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!

Share this post


Link to post
Share on other sites

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);
}

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...