本文介紹利用動態建立層技術實現無冗餘代碼為表單自動添加錯誤提示的方法。
項目中表單輸入檢測是基本必定會碰到的,本文提供一種方法通過js動態建立層的方法為表單添加錯誤提示。該代碼在IE6和firefox3.5中測試通過。
動態建立層的代碼:
function createDiv(msg){ //create a new empty p var str = document.createElement("p"); str.id = "newp"; //p ID str.innerHTML=msg; // content document.body.appendChild(str); // add it to document body return str; // return the new p}
通過調用上面函數基可以建立一個層:
var msg="X| 請輸入資料!";var newp = createDiv(msg); // msg 為層內內容
我們可以用css對建立的曾定義樣式,可以採用id或者class的方式。下面通過直接指定id的方式:
<style type="text/css"> p#newdv{width:120px;height:16px;padding-top:2px;border:solid 1px red;position:absolute;background-color:red;color:#fff;font-size:12px;}</style>
當我們提交表單時,就可以對各個表單進行檢驗了,當檢驗到某表單不合法,我們需要在該表單的位置給出錯誤提示。步驟是:先找出該表單的位置,然後以錯誤資訊建立錯誤提示新層,將層的位置設定在該表單上。
function submit(){ var item = document.getElementById("itemId"); // itemId is the wrong input item var left=item.offsetLeft+(item.style.width.replace("px",""))/1; // get the item left position var top=item.offsetTop; // get the item top position // create new p: var msg="X| 請輸入資料!"; var newp = createDiv(msg); // set the p position: newp.style.left=left; newp.style.top=top;}