如何在foreach循环中使用“for”属性

时间:2018-04-23 20:34:00

标签: javascript html css

我的项目中有一个自定义单选按钮。问题是这个按钮不能在for循环中的web表单中工作。因为这些使用“for”属性来选择输入字段的唯一id。但是对于我的项目,我需要这些单选按钮才能在foreach循环中工作。我已经尝试过但无法找到解决方案。我在javascript中有一些方法可以做到这一点吗?

@import url(http://fonts.googleapis.com/css?family=Lato:300,400,900);
* {
  box-sizing: border-box;
}
@media (max-width: 40em) {
  .button-wrap {
    margin-top: -1.5em;
  }
}

.button-label {
  display: inline-block;
  padding: 0.5em 1.5em;
  margin: 0.5em;
  cursor: pointer;
  color: #292929;
  border-radius: 0.25em;
  background: #efefef;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2), inset 0 -3px 0 rgba(0, 0, 0, 0.22);
  -webkit-transition: 0.3s;
  transition: 0.3s;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.button-label h1 {
  font-size: 1em;
  font-family: "Lato", sans-serif;
  margin-top:10px;
  font-weight: 700;
}
.button-label:hover {
  background: #d6d6d6;
  color: #101010;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2), inset 0 -3px 0 rgba(0, 0, 0, 0.32);
}
.button-label:active {
  -webkit-transform: translateY(2px);
          transform: translateY(2px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2), inset 0px -1px 0 rgba(0, 0, 0, 0.22);
}
@media (max-width: 40em) {
  .button-label {
    padding: 0em 1em 3px;
    margin: 0.25em;
  }
}

#yes-button:checked + .button-label {
  background: #2ECC71;
  color: #efefef;
}
#yes-button:checked + .button-label:hover {
  background: #29b765;
  color: #e2e2e2;
}


#no-button:checked + .button-label {
  background: #D91E18;
  color: #efefef;
}
#no-button:checked + .button-label:hover {
  background: #c21b15;
  color: #e2e2e2;
}



.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<body>
   <input class="hidden radio-label" type="radio" name="optradio" value="strongPositive"  id="yes-button"/>
   <label class="button-label" for="yes-button"><h1>option</h1></label>
  <input class="hidden radio-label" name="optradio" value="meduimPositive" type="radio"  id="no-button"/>
  <label class="button-label" for="no-button"><h1>option2</h1></label>

</body>
</head>
</html>

1 个答案:

答案 0 :(得分:2)

您不需要id。如果您将<input>包裹在<label>中,则<label>会自动与<input>相关联。

<label><input type="radio" name="test" value="1"> Text 1</input></label>
<label><input type="radio" name="test" value="2"> Text 2</input></label>

请参阅MDN's <label> Usage Notes

  
      
  • 通过放置,<label>可以与控件相关联   <label>元素内的控制元素,或者使用for   属性。这种控制称为标签的标记控制   元件。一个输入可以与多个标签相关联。
  •   

如果你找到了一个绝对必须 id(可能是额外的aria属性)的原因,我建议你创建一个静态索引变量,你可以递增并分配给你实例化小部件的新实例。这是我通常遵循的模式,也是Dojo遵循的模式。