问题
After creating new classroom, the data will then be send to a list as shown on here:
Now, how do I add/make (a) link/s into every classroom so that whenever I click it it will redirect me to a page and show me their specific data like ClassroomID, students, etc.
here's the code:
//retrieving
var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function (data) {
var roomNames = data.val().TheClass;
var ul = document.createElement('ul');
document.getElementById('myList').appendChild(ul);
var li = document.createElement('li');
ul.appendChild(li);
Object.keys(roomNames).forEach(function (key) {
li.innerHTML += roomNames[key];
});
});
//adding
function classcreation(q) {
var checkcn = document.getElementById('classroomName').value;
if (checkcn == "" && checkcn == null) {
alert("Empty Class Name!!");
} else {
var usuid = generateId();
var myClasses = {};
myClasses.TheClass = document.getElementById('classroomName').value;
myClasses.Teacher = user.displayName;
myClasses.TeacherID = user.uid;
myClasses.ClassID = usuid;
fbclass.child(user.uid).push().set(myClasses);
}
}
function generateId() {
return 'xxxx-xxxx-xxxx'.replace(/[x]/g, function () {
return (Math.random() * 9 | 0).toString();
})
}
回答1:
I think what you are looking for is adding an Anchor tag within your li which on click would redirect you to a page where class details are shown. If that is the case edit the following line in your code to (if template string works else use string concatenation to create appropriate string)
li.innerHTML += `<a href=${link}>roomNames[key]</a>`
If you want to add the classroom details within same HTML without redirecting user try following.
This will append a div to existing HTML where you will show the class info.
var infoDiv = document.createElement('div');
infoDiv.id = 'classInfo';
On your ul add onclick listener with the following function.
ul.onclick = (e) => {
document.getElementById('classInfo').innerHTML = generateClassInfo(e.target.name);
}
And to your li add name which uniquely identifies a class.
li.name= identifier
Adding onclick to ul instead of li reduces the number of onclick listeners which is basically a performance optimization.
Take a look at the code sandbox for working example. https://codesandbox.io/s/q9w9x0vlww
来源:https://stackoverflow.com/questions/52446430/how-to-add-links-in-my-list-and-retrieve-the-data