HTML 屬性:for

for 屬性是 <label><output> 允許使用的屬性。當用於 <label> 元素時,它指示該標籤所描述的表單元素。當用於 <output> 元素時,它允許表示用於輸出的值的元素之間建立明確的關係。

試一試

<p>
  <label>First Name (no "for" attribute):</label>
  <input id="first" type="text" value="Jane" />
</p>
<p>
  <label for="last">Last Name (w/ "for" attribute):</label>
  <input id="last" type="text" value="Doe" />
</p>
<p id="result">
  <strong id="result-label">Full Name:</strong>
  <output for="first last" aria-labelledby="result-label" id="output"></output>
</p>
label[for="paragraph"] {
  color: rebeccapurple;
}

#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">Your name</label> <input type="text" id="username" />

當用作 <output> 的屬性時,for 屬性的值是用於建立輸出的元素 ID 值的空格分隔列表。

html
<input type="range" id="b" name="b" value="50" /> +
<input type="number" id="a" name="a" value="10" /> =
<output name="result" for="a b">60</output>

示例

有關用法示例,請參閱 <label><output> 的元素頁面。

規範

規範
HTML
# attr-label-for
HTML
# attr-output-for

瀏覽器相容性

html.elements.label.for

html.elements.output.for