整理了幾段比較實用的JavaScript表單代碼段,分享給大家參考,具體內容如下:
onload方法在頁面加載完成後自動調用,因此被广泛使用,但弊端是只能用onload執行一個方法。下面這段程式碼可以保證多個方法在onload時執行:
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
str.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g,"");
str.replace(/[\u4e00-\u9fa5]/g,"");
xxx.oncopy = function(){ return false; }
xxx.onpaste = function(){ return false; }
主要思想是需要三個數據:限制輸入的長度、已經輸入了多長、截取多少個字符。由於JS的截取方法不區分中英文,「哈哈哈」和「haha」的 substr(0,2) 結果不同,但如果按編碼「一個漢字對應2個字符、一個字母對應1個字符」來算,統計真實長度時應該是「字符的長度 + 漢字的個數」。例如限制輸入5個字符,輸入「哈哈」後就只能再輸入一個h。
var strLength = function(_str,_model){
_model = _model || "Ch"; //En模式下,中文算作1字符;Ch模式下,中文為2個字符
var _strLen = _str.length; //獲取字符串長度
if(_strLen == 0){
return 0;
}else{
var chinese = _str.match(/[\u4e00-\u9fa5]/g); //匹配中文
return _strLen + (chinese && _model == "Ch"?chinese.length:0);
}
}
var funcRemainingCharacters = function(){
remainingCharacters = document.getElementById("remainingCharacters");
var clearRemainingCharacters = function(_this){
var _value = _this.value;
var _valueLength = _value.length;
var dataLength = _this.getAttribute("data-length");
var dataModel = _this.getAttribute("data-model");
var subLen = dataLength;
if(dataModel == "Ch"){//僅當開啟Ch後,才對重新計算截取的長度
_valueLength = strLength(_value,dataModel);
var vv = _value.match(/[\u4e00-\u9fa5]/g);
subLen = dataLength - (!vv?0:vv.length);
}
if(_valueLength > dataLength){
_this.value = _value.substr(0,subLen);
}
}
remainingCharacters.onfocus = function(){
clearRemainingCharacters(this);
}
remainingCharacters.onkeyup = function(){
clearRemainingCharacters(this);
}
remainingCharacters.onblur = function(){
clearRemainingCharacters(this);
}
}
addLoadEvent(funcRemainingCharacters);
var setCSS = function(_this,cssOption){
if(!_this || _this.nodeType === 3 || _this.nodeType === 8 || !_this.style){
return;
}
for(var cs in cssOption){
_this.style[cs] = cssOption[cs];
}
return _this;
};
使用時:
setCSS(xxx,{ "position":"relative", "top":"0px" });
採用scrollHeight複製給style.height:
xxx.style.overflowY = "hidden";
xxx.onkeyup = function(){
xxx.style.height = xxx.scrollHeight+"px";
};
//下面是js代碼
var targets = document.getElementsByName("actionSelects");
var targetsLen = targets.length;
var i = 0;
document.getElementById("allSelect").onclick = function(){
for(i=0;i<targetsLen;i++){
targets[i].checked = true;
}
}
document.getElementById("cancelAllSelect").onclick = function(){
for(i=0;i<targetsLen;i++){
targets[i].checked = false;
}
}
document.getElementById("_select").onclick = function(){
for(i=0;i<targetsLen;i++){
targets[i].checked = !targets[i].checked;
}
}
希望本文所述對大家學習JavaScript程式設計有所幫助。