我如何在javascript函数内为div添加类

时间:2019-05-28 13:54:30

标签: javascript html

我需要在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;
}

2 个答案:

答案 0 :(得分:1)

正如其他人所说,有两种方法:.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()

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

答案 1 :(得分:0)

您可以在追加之后将class添加到div,例如:

    function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                            "<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
                            "<strong>Phone :</strong>  " + agency.phone + "<br></div>"
                        ).addClass("CLASSNAME1 CLASSNAME2");
                    });
                }