防止在动态创建的输入元素上关闭标签?

时间:2019-10-13 23:20:57

标签: javascript html input

将元素添加到列表项并添加一个子元素后,浏览器将生成无效的标记。如何防止这种情况发生?在元素检查器中,创建的元素在那里,但是我看不到它们或选择它们的内容。 我把整个代码放在这里: https://codepen.io/elenderg/pen/eYYJxqg

var Matricula = "<strong>PAM5913</strong><br>";
var Velocidade = "N0250";
var Origem ="SBHT&emsp;";
var Destino = "<strong>SBBE</strong><br>";
var Hora = "<strong>1600</strong>"
var Tipo = "E195M"
var Transponder = "6721";
var Nível = "F370";
var Rota = "DCT";

function CriaStrip(){
var Ul = document.getElementById('ul');
var Li = document.createElement('li');

Li.setAttribute("class", "cinza li");

var Input = document.createElement('input');

Input.setAttribute('name', 'painel');
Input.setAttribute("type","radio");
Input.setAttribute("id","input1");

var Label = document.createElement('label')
Label.htmlFor = 'input1';

var Div1 = document.createElement('div');

Div1.setAttribute("class", "lado-a-lado");
Div1.innerHTML = Matricula + Origem + Destino + Hora + Tipo;


var Div2 = document.createElement('div');

Div2.setAttribute("class", "dados");
Div2.innerHTML = Transponder + Nível + Rota + "<br><br>" + Velocidade;



Ul.appendChild(Li);
Li.appendChild(Input);
Input.appendChild(Label);
Label.appendChild(Div1);
Div1.appendChild(Div2);


}
.painel{
    border: 4px solid rgb(0,0,255) ;
    width: 50%;
    background-color: black;
}
.cinza{
    background-color: gray;
    border-bottom: 1px solid silver;;
    
}
.ul{
    margin:0px;
    padding: 0px;
    list-style: none;  
}
.li{
    border: 1px solid #ccc;
    box-sizing: border-box;
    position: relative;
    height: 70px;
}
.li label{
    bottom: 1px;
    left: 1px;
    right: 1px;
    top: 1px;
    display: block;    
    position: absolute;
}
input[type="radio"]{
  display: none;
}
.lado-a-lado{
    display: -webkit-box;    
}
.dados{
    padding-left: 3px;
}
.ul input:checked + label {
    border-right: 8px solid white;
  }
<div class="painel" onclick="CriaStrip()"> 
        <ul class="ul" id="ul">
            <li class="cinza li" id="li">  
                    Click to create new items           
            </li>
        </ul>
    </div>

1 个答案:

答案 0 :(得分:0)

我只需要更改您添加标签的方式。您应该将其附加到Li而不是Input

Ul.appendChild(Li);
Li.appendChild(Input);
Li.appendChild(Label); // From Input to Li
Label.appendChild(Div1);
Div1.appendChild(Div2);