required屬性:在提交時洒扎,如果元素中內(nèi)容為空白辑甜,則不允許提交,同時在瀏覽器中會彈出提示文字袍冷。
autofocus屬性:當頁面打開時磷醋,該控件自動獲得光標焦點
required屬性和autofocus屬性的代碼如下:
<!DOCTYPE html>
<head>
<title>required屬性和autofocus屬性 的使用示例</title>
<meta charset="UTF-8">
</head>
<form action="demo_form.asp" method="get">
Name: <input type="text" name="usr_name" required="required" autofocus />
<!--autofocus:當頁面打開時,該控件自動獲得光標焦點 -->
<input type="submit" />
<!-- 提交按鈕 -->
<input type="reset" />
<!-- 重置按鈕 -->
</form>
</form>
運行如圖:
當不輸入內(nèi)容胡诗,點擊按鈕就會出現(xiàn)下圖:
labels屬性:為所有可用標簽(label元素)的表單元素定義一個label屬性子檀,屬性值為一個NodeList對象,代表該元素所綁定的標簽元素所構成的集合乃戈。
labels屬性的使用方法:
<!DOCTYPE html>
<head>
<title>labels屬性的使用示例</title>
<meta charset="UTF-8">
</head>
<script type="text/javascript">
function Validate(){
var txtName=document.getElementById("txt_name"); //找到輸入框
var button=document.getElementById("btnValidate");//找到按鈕
var form=document.getElementById("testform");//找到表單
if(txtName.value.trim()==""){//判斷輸入框里有文字沒褂痰,trim()就是空格的意思
if(txtName.labels.length==1)//判斷輸入框里的索引是不是為1
// 0是id=label 1是id="txt_namez
//疑問:這里的索引和for綁定不太明白
{
var label=document.createElement("label");//是在對象中創(chuàng)建一個對象,
label.setAttribute("for","txt_name");
//輸出:for="txt_name" 疑問:本來在label中就是for="txt_name"為什么還要寫症虑?
// setAttribute(string name(字符串名稱), string value(字符串值)):增加一個指定名稱和值的新屬性缩歪,或者把一個現(xiàn)有的屬性設定為指定的值。
form.insertBefore(label,btnValidate); //btnValidate/txt_name/button
//在節(jié)點的子節(jié)點列表任意位置插入新的節(jié)點谍憔。
txtName.labels[1].innerHTML="請輸入姓名";//插入引號里的內(nèi)容
//labels[1]指id="txt_name"
txtName.labels[1].setAttribute(
"style","font-size:20px; color:red");
//輸出:style{font-size:20px; color:red};
}
}
else if(txtName.labels.length>1)
form.removeChild(txtName.labels[1]);//提交后刪除輸入框里的內(nèi)容
// removeChild() 方法指定元素的某個指定的子節(jié)點匪蝙。
// 以 Node 對象返回被刪除的節(jié)點,如果節(jié)點不存在則返回 null习贫。
}
</script>
<form id="testform">
<label id="label" for="txt_name">姓名:</label>
<input id="txt_name" autofocus><!--autofocus:當頁面打開時逛球,該控件自動獲得光標焦點 -->
<input type="button" id="btnValidate" value="驗證" onclick="Validate()"/>
</form>
代碼運行如圖:
不在輸入框輸入內(nèi)容點擊按鈕就會出現(xiàn)下圖:
在這串代碼中<label id="label" for="txt_name">姓名:</label>for 屬性應該等于相關元素的 id 元素,以便將它們捆綁起來苫昌。
for的值有兩個:
第一個:id ( 規(guī)定 label 綁定到哪個表單元素颤绕。)
第二個:formid (規(guī)定 label 字段所屬的一個或多個表單。)
document.createElement()是在對象中創(chuàng)建一個對象祟身,要與appendChild() 或 insertBefore()方法聯(lián)合使用奥务。
appendChild() 方法在節(jié)點的子節(jié)點列表末添加新的子節(jié)點。
insertBefore() 方法在節(jié)點的子節(jié)點列表任意位置插入新的節(jié)點袜硫。
innerHTML在JS是雙向功能:
獲取對象的內(nèi)容 或 向對象插入內(nèi)容氯葬;
如:
<div id="aa">這是內(nèi)容</div> ,我們可以通過 document.getElementById('aa').innerHTML 來獲取id為aa的對象的內(nèi)嵌內(nèi)容婉陷;
也可以對某對象插入內(nèi)容帚称,
如:
document.getElementById('abc').innerHTML='這是被插入的內(nèi)容'; 這樣就能向id為abc的對象插入內(nèi)容官研。