function render(recievedData) {
let a = 0;
const info = JSON.parse(recievedData);
console.log(info);
if (info[a] === null)
return;
else {
info.forEach(element => {
console.log(element);
var newdiv = document.createElement('div');
console.log(newdiv);
newdiv.className = 'card';
console.log(newdiv);
var newdivforname = document.createElement('div');
var newdivformood = document.createElement('div');
var newdivforlatitude = document.createElement('div');
var newdivforlongitude = document.createElement('div');
newdivforname.innerText = element.name;
newdivformood.innerText = element.mood;
newdivforlatitude.innerText = element.latitude;
newdivforlongitude.innerText = element.longitude;
console.log(newdiv);
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforname));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivformood));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforlatitude));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforlongitude));
我在使用javascript创建newdiv后添加了一些样式,但它没有反映任何变化。虽然当我控制台log newdiv它显示附加的css。
HTML
<div id="datastore"></div>
CSS
.card{
font: 900;
color: red;
background: lightgreen;
}
我找到问题了。
您正在使用
.newdiv
在CSS。
你只需要添加newDivforlike元素
如:-
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforname));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivformood));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforlatitude));
document.getElementById("datastore").appendChild(newdiv.appendChild(newdivforlongitude));
与
相同document.getElementById("datastore").appendChild(newdivforname);
document.getElementById("datastore").appendChild(newdivformood);
document.getElementById("datastore").appendChild(newdivforlatitude);
document.getElementById("datastore").appendChild(newdivforlongitude);
so,要解决这个问题,
您需要首先附加所有'newDivfor'元素。
然后将newdiv元素附加到数据存储
ie: -
答案
newdiv.appendChild(newdivforname);
newdiv.appendChild(newdivformood);
newdiv.appendChild(newdivforlatitude);
newdiv.appendChild(newdivforlongitude);
document.getElementById("datastore").appendChild(newdiv)
您的代码没有显示动态添加CSS样式到.card
(newdiv)。你可以这样做:
JS
//After the newdiv is created
document.querySelector('.card').style.color = "red";
//Other styles can be added likewise