HTML DOM Label htmlFor 属性

htmlweb developmentfront end technology更新于 2025/6/23 2:20:17

HTML DOM Label htmlFor 属性返回/设置 for 属性的值。

语法

以下是语法 −

返回 for 属性 − 的值

labelObject.htmlFor

示例

让我们看一个 Label htmlFor 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<title>Label htmlFor</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Label-htmlFor</legend>
<label id="CurrentEditor" for="editorTwo">Current Editor:</label><br>
<input type="text" id="editorOne" placeholder="editorOne">
<input type="text" id="editorTwo" placeholder="editorTwo">
<input type="button" onclick="getEventData()" value="Change Editor">
<div id="divDisplay">Label for attribute set as editor two</div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var labelSelect = document.getElementById("CurrentEditor");
   function getEventData() {
      if(labelSelect.htmlFor === 'editorTwo'){
         divDisplay.textContent = 'Label for attribute set as editor one';
         labelSelect.htmlFor = 'editorOne';
      }
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"更改编辑器"按钮之前 −

点击"更改编辑器"按钮之后 −


相关文章


有用资源