我想知道如何在html中创建多个“相同”的input type。我有一个网格,并希望为每行提供一些选择。我想对每个label应用一个input type,但是我遇到了如何在input typelabel属性中引用每个for的问题。由于for使用id,并且我有多个相同input type的实例,因此我该如何参考input type而不会做诸如id='button0'id='button1'id='button2'和等等吗?

例如(为简单起见,代码被精简,而我使用的是kendo-ui样式),

<div class="row">
    <div class="col">
        <p>This is a column</p>
        <input type="checkbox" class="k-checkbox" id="select-this">
        <label class="k-checkbox-label" for="select-this">Select this</label>
    </div>
</div>
<div class="row">
    <div class="col">
        <p>This is another column</p>
        <input type="checkbox" class="k-checkbox" id="select-this">
        <label class="k-checkbox-label" for="select-this">Select this</label>
    </div>
</div>


明智的做法是让两个元素具有相同的id(在本例中为id="select-this"),并且for似乎无法引用class。有没有更好的方法使用某些工具(例如jQuery)来做到这一点,还是有解决方法?

最佳答案

您可以创建一个脚本,以动态设置所有id并将那些新的id设置为标签for属性。



window.onload = function(){
  for(let tL=document.querySelectorAll('.k-checkbox'), i=0, j=tL.length; i<j; i++){
    var tLabel = tL[i].parentNode.querySelector('label.k-checkbox-label');
    if(tLabel){
      tL[i].name = tL[i].id = 'whatever' + i;
      tLabel.setAttribute('for', tL[i].id)
    }
  }
}

<div class="row">
    <div class="col">
        <p>This is a column</p>
        <input type="checkbox" class="k-checkbox">
        <label class="k-checkbox-label" for="select-this">Select this</label>
    </div>
</div>
<div class="row">
    <div class="col">
        <p>This is another column</p>
        <input type="checkbox" class="k-checkbox">
        <label class="k-checkbox-label" for="select-this">Select this</label>
    </div>
</div>

关于javascript - 同一按钮的多个实例的标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51204085/

10-11 05:55
查看更多