使用javascript在html页面中动态添加多个标签

Add multiple label dynamically in html page using javascript

本文关键字:添加 动态 标签 javascript html 使用      更新时间:2023-09-26

我使用以下代码动态添加标签:

  var array_resp=[CorrectStreet,CorrectCity,CorrectState,CorrectZip];
        // var stateName=map.getKey(CorrectState);
          if(array_resp.length > 0) {
                var answers = [];
                for(var i = 0; i <= array_resp.length - 2; i++) {
                    answers[i] = document.createLabel({
                        color : '#000',
                        text : array_resp[i],
                        top : top,
                        left : '30 px',
                        width : '420 px',
                        height : '100 px',
                        visible : 'true',
                        backgroundColor : 'white',
                        font : FontNormal,
                    });
                   document.body.appendChild(answers[i]);
                }
            }   
在html

: -

    <button onclick="myFunction()">Try it</button>

但它没有给出正确的输出,当我点击按钮。为什么会这样?

代码中的一些问题:

  1. createLabel没有创建LABEL元素的功能
  2. 以错误的方式分配样式/属性,永远不要在对象类型
  3. left, width &高度。

试试这个:

<body>
    <script>
    function myFunction(){
        var array_resp=['CorrectStreet','CorrectCity','CorrectState','CorrectZip'];
        // var stateName=map.getKey(CorrectState);
        if(array_resp.length > 0) {
            for(var i = 0; i <= array_resp.length - 2; i++) {
                var label = document.createElement('label');
                label.style.color = '#000';
                label.style.top = 'top';
                label.style.left = '30px';
                label.style.width = '420px';
                label.style.height = '100px';
                label.style.visible = 'true';
                label.style.backgroundColor = 'white';
                label.style.font = 'FontNormal';
                label.innerHTML = array_resp[i];
                document.body.appendChild(label);
            }
        }
    }
    </script>
    <button onclick="myFunction()">Try it</button>
</body>