伙计们,我需要在javascript函数内为div添加一个类。我想在每个gency_nameADRESS_TEXTphone处放一个盒子我该怎么做

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


确保您调用课程jsFilt(someValue)的函数

如果您打开浏览器控制台,我会在代码中添加一些console.log('bla bla'),您会看到一些消息已被打印出来,并且可以帮助您跟踪问题。一切正常后,您可以删除console.log()

因此,这可能有效或可能存在一些语法错误。让我知道您是否可以使用它

10-05 20:42
查看更多