此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
HTML 属性:for
for 属性是<label> 和<output> 允许使用的属性。当用于<label> 元素时,它表示该标签所描述的表单元素。当用于<output> 元素时,它允许在代表输出中使用的值的元素之间建立明确的关系。
In this article
尝试一下
<p> <label>First Name (no "for" attribute):</label> <input type="text" value="Jane" /></p><p> <label for="last">Last Name (w/ "for" attribute):</label> <input type="text" value="Doe" /></p><p> <strong>Full Name:</strong> <output for="first last" aria-labelledby="result-label"></output></p>label[for="paragraph"] { color: rebbeccapurple;}#result { text-align: center;}#result-label { font-size: 16pt;}#result-label,#output { display: block;}const firstNameEl = document.getElementById("first");const lastNameEl = document.getElementById("last");const outputEl = document.getElementById("output");function updateOutput() { const value = `${firstNameEl.value} ${lastNameEl.value}`; outputEl.innerText = value;}updateOutput();firstNameEl.addEventListener("input", updateOutput);lastNameEl.addEventListener("input", updateOutput);使用说明
当作为<label> 的属性使用时,for 属性的值是与之相关的表单元素的id。
html
<label for="username">你的名字</label> <input type="text" />作为<output> 的属性使用时,for 属性的值是一个空格分隔的列表,其中包含用于创建输出的元素的id 值。
html
<input type="range" name="b" value="50" /> +<input type="number" name="a" value="10" /> =<output name="result" for="a b">60</output>示例
规范
| Specification |
|---|
| HTML> # attr-label-for> |
| HTML> # attr-output-for> |