使用 For 和 Form 属性的输出元素
以下演示以 <output> 元素使用 [for] 和 [form] 属性为特色。请记住,<output> 需要 JavaScript 才能运行。如本例所示,内联 JavaScript 通常用于表单中。虽然 <input> 元素是 type="number",但它们的 values 不是数字,它们是文本。因此,如果你需要计算 values,则必须使用以下方法将每个 value 转换为数字:parseInt(),parseFloat(),Number() 等。
<!--form1 will collect the values of in1 and in2 on 'input' event.-->
<!--out1 value will be the sum of in1 and in2 values.-->
<form id="form1" name="form1" oninput="out1.value = parseInt(in1.value, 10) + parseInt(in2.value, 10)">
<fieldset>
<legend>Output Example</legend>
<input type="number" id="in1" name="in1" value="0">
<br/>
+
<input type="number" id="in2" name="in2" value="0">
</fieldset>
</form>
<!--[for] attribute enables out1 to display calculations for in1 and in2.-->
<!--[form] attribute designates form1 as the form owner of out1 even if it isn't a descendant.-->
<output name="out1" for="in1 in2" form="form1">0</output>