伙计们,我需要在 javascript 函数内添加一个 div 类。我想为每个gency_name
、ADRESS_TEXT
和phone
放一个盒子,我该怎么做
function jsFilt(value) {
document.getElementById("myDiv").innerHTML = "";
value.AGENCY.forEach(agency => {
$("#myDiv").append(
//HERE "<div class ="xxx" style='border-style:ridge' ><strong>Agency Name :</strong> " + agency.agency_name + "<br>" +
"<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
"<strong>Phone :</strong> " + agency.phone + "<br></div>"
);
});
}
CSS
.xxx{
width: 220px;
padding: 10px;
border: 5px solid gray;
margin: 0px;
}
最佳答案
正如其他人所说,有两种方法: .addClass('classname1 classname2')
和 .attr('class','classname1 classname2')
但 addClass
更好
在你的情况下会是这样的:
function jsFilt(value) {
console.log('running jsFilt');
//document.getElementById("myDiv").innerHTML = "";
$('#myDiv').html(''); // this is jquery way of doing it
console.log('myDiv is now empty');
value.AGENCY.forEach(agency => {
console.log('inside loop');
//first we create that div and give it class and style
const $div = $('<div></div>').addClass('xxx').attr('style','border-style:ridge;');
// here we set innerHTML
$div.html(`
<strong>Agency Name :</strong> ` + agency.agency_name + `<br>
<strong>Adress : </strong> ` + agency.ADRESS_TEXT + `<br>
<strong>Phone :</strong> ` + agency.phone + `<br>
`);
console.log('here is the div we created:',$div);
// here we append it to the container (#myDiv)
$("#myDiv").append($div);
console.log('this is how myDiv looks like now', $("#myDiv"));
});
}
确保您调用了类(class)函数 jsFilt(someValue)
我在我的代码中添加了一些 console.log('bla bla')
如果您打开浏览器控制台,您可以看到一些消息正在打印出来,它可以帮助您跟踪问题。一切正常后,您可以删除 console.log()
s
所以这可能有效,也可能有一些语法错误。如果你能让它工作,请告诉我
关于javascript - 如何在 javascript 函数内部添加 div 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56343829/