I am getting problem in script as follows:
My code
function data (classno) {
switch (classno) {
case 0:
return [
{'name' : 'SomeName1', 'age' : 'SomeAge1'},
{'name' : 'SomeName2', 'age' : 'SomeAge2'}
]
break;
case 2:
return [
{'name' : 'SomeName3', 'age' : 'SomeAge3'},
{'name' : 'SomeName4', 'age' : 'SomeAge4'}
]
}
}
function add (name, age, classno) {
var a, b;
a = {'name' : name, 'age' : age};
b = data(classno);
b.push(a);
}
function list (classno) {
var dt = data(classno),
body = document.body;
for (var x=0;x < dt.length;x++) {
var div = document.createElement('div');
var div1 = document.createElement('div');
var tx_name = document.createTextNode(dt[x].name);
var tx_age = document.createTextNode(dt[x].age);
div1.appendChild(tx_age);
div.appendChild(tx_name);
div.appendChild(div1);
body.appendChild(div)
}
}
add('ABC', 12, 0); //Adding User to list...
list(0); //Listing all user in Class number '0'...
But, the new user which I added not shown in listed users.
Is there any other way to do so?
Here's my JSFiddle which I tried.
data
always return a new array, there is no variable in which this array is stored so that you can update that array and get the updated data.
check this updated fiddle to see how you can do it without creating a variable array but then you won't be able to invoke the list method by passing classno
.
However, check this fiddle to see how you can do it with variable array and still use list method by passing classno
var obj = {
0: [
{'name' : 'SomeName1', 'age' : 'SomeAge1'},
{'name' : 'SomeName2', 'age' : 'SomeAge2'}
],
2: [
{'name' : 'SomeName3', 'age' : 'SomeAge3'},
{'name' : 'SomeName4', 'age' : 'SomeAge4'}
]
}
function data (classno) {
return obj[ classno ];
}
function add (name, age, classno) {
var a, b;
a = {'name' : name, 'age' : age};
b = data(classno);
b.push(a);
}
function list (classno) {
var dt = data(classno),
body = document.body;
for (var x=0;x < dt.length;x++) {
var div = document.createElement('div');
var div1 = document.createElement('div');
var tx_name = document.createTextNode(dt[x].name);
var tx_age = document.createTextNode(dt[x].age);
div1.appendChild(tx_age);
div.appendChild(tx_name);
div.appendChild(div1);
body.appendChild(div)
}
}
add('ABC', 12, 0); //Adding User to list...
list(0); //Listing all user in Class number '0'...
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.