简体   繁体   English

“ for”属性的目的是什么?

[英]What is the purpose of the “for” attribute?

In this code taken from angular.org: 在这段来自angular.org的代码中:

<script>
   function Ctrl($scope) {
     $scope.names = ['pizza', 'unicorns', 'robots'];
     $scope.my = { favorite: 'unicorns' };
   }
</script>
 <form ng-controller="Ctrl">
   <h2>Which is your favorite?</h2>
     <label ng-repeat="name in names" for="{{name}}">
       {{name}}
       <input type="radio"
              ng-model="my.favorite"
              ng-value="name"
              id="{{name}}"
              name="favorite">
     </label>
   <div>You chose {{my.favorite}}</div>
 </form>

the label element has a "for" statement. label元素具有“ for”语句。 I can't find anything on the Angular.org site indicating what this is or how it is used. 我在Angular.org网站上找不到任何指示它是什么或如何使用的东西。 It's not listed under directives or functions. 它未在指令或功能下列出。

It's an HTML attribute used to help browsers see the field that a label is "attached" to. 这是一个HTML属性,用于帮助浏览器查看标签“附加”到的字段。

Example: Try clicking on some labels and your browser will automatically focus on the input field that it is associated with. 示例:尝试单击一些标签,您的浏览器将自动关注与之关联的输入字段。

[PS] It has nothing to do with Angular and more of HTML and accessibility. [PS]与Angular无关,与HTML和可访问性无关。

Just adding to the comments in the previous answer: 只需添加上一个答案中的注释即可:

The for attribute is used to target the input when the label and input are separate, like so: label和输入分开时, for属性用于将input作为目标,如下所示:

<label for="MyId">
  My Label
</label>

<input type="radio"
       id="MyId"
       name="favorite">

If you nest the input inside the label like your example: 如果像示例一样将input嵌套在label内:

<label>
  My Label

  <input type="radio"
         name="favorite">
</label>

Then you don't need the for attribute, it will automatically target the input inside the label. 然后,您不需要for属性,它将自动定位标签内的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM