论坛首页 Web前端技术论坛

常用JS代码实例

浏览 42217 次
精华帖 (2) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (18)
作者 正文
   发表时间:2009-03-26  
很不错,有些用法很经典。。
0 请登录后投票
   发表时间:2009-03-27  
很感谢啊 !!! 支持啊!多发一点啊!
0 请登录后投票
   发表时间:2009-03-27  
对网友的Jquery问题的解答
问题如下:
这样的选择器怎么写
<div drag="true" index="1"></div>
<div drag="true" index="2"></div>
<div drag="true"></div>
找到drag="true" 并且 index="1" 或 无index属性的div,这样的选择器怎么写


解决思路:
1. 找到drag="true" 并且 index="1"
$('div[drag="true"][index="1"]')

2. 找到drag="true" 并且  无index属性的
$("div[drag='true']:not([index])")

3. 将三者联立起来
$("div[drag='true']:not([index]),div[drag='true'][index='1']")

在解答的过程中,我只能解决前两步,呵呵,对于取或操作不知道.
谢谢网友@一切皆有可能 的分享
0 请登录后投票
   发表时间:2009-03-28  
网上有这样一道题目:

一个字符串String=“adadfdfseffserfefsefseetsdg”,找出里面出现次数最多的字母和出现的次数。

经典的解答思路为:取出字符串的第一个字符(首字母),利用的字符串的 replace 方法将符合正则表达式(第一个字符)替代为空,此字母出现的次数为原始的字符串长度减去替代后的字符串长度。循环迭代找出长度最长的字母。

<script type="text/javascript">  var str ="adadfdfseffserfefsefseeffffftsdg"; //命名一个变量放置给出的字符串var maxLength = 0; //命名一个变量放置字母出现的最高次数并初始化为0var result = ''; //命名一个变量放置结果输入  while( str != '' ){ //循环迭代开始,并判断字符串是否为空        oldStr = str; //将原始的字符串变量赋值给新变量        getStr = str.substr(0,1); //用字符串的substr的方法得到第一个字符(首字母)        eval("str = str.replace(/"+getStr+"/g,'')"); //详细如补充          if( oldStr.length-str.length > maxLength ) { //判断原始的字符串的长度减去替代后字符串长度是否大于之前出现的最大的字符串长度                maxLength = oldStr.length-str.length; //两字符串长度相减得到最大的字符串长度                result = getStr + "=" + maxLength //返回最大的字符串结果(字母、出现次数)        }}  alert(result) //弹出结果  </script>



补充:

eval("str = str.replace(/"+getStr+"/g,'')");

可能很多人想这样写 str = str.replace(/getStr/g,”),可结果却是会出错的。为什么呢,在这句中正则表达式匹配的是 getStr 字符串,而不是 getStr 指向的首字母。通过 eval 方法可以避免(首先 getStr 得到指向的首字母,用字符串连接 “str = str.replace(/”+getStr+”/g,”)”,最后在 eval 中执行这段代码,即:先解释Javascript 代码,然后再执行它)。

由于 eval 性能不好,容易出错,而且可读性不好。建议将
eval(”str = str.replace(/”+getStr+”/g,”)”)
改为:

str = str.replace(new RegExp(getStr,"g"),"")
0 请登录后投票
   发表时间:2009-04-03  
//对 jQuery.iamsese 添加两个实用方法,本人在开发中使用的


	/**
	 * 解析URL查询字符串,传入的参数是经过处理后的 url ? 号后的内容
	 * 返回一个对象
	 * @param {} str
	 * @return {}
	 */
	getQueryString : function(str){
		var allargs = $.trim(str) ;		
		var requestObject = {} ;		
		if (allargs != ''){
			//分割成数组
			allargs = allargs.split("&");
			jQuery.each(allargs,function(k,v){
				var bb = v.split("=");
				eval('requestObject.' + bb[0] + "='" + bb[1] + "';");
			});
		}
		
		allargs = null ;
		return requestObject ;
	} ,
	/**
	 * 从对象生成查询格式的字符串
	 * @param {} obj
	 * @return {}
	 */
	buildQueryString : function(obj){
		var hurl_str = '' ;
		jQuery.each(obj,function(k,v){
			hurl_str += k + '=' + v + '&' ;
		});
		return hurl_str.replace(/&$/, '') ;
	} 	
0 请登录后投票
   发表时间:2009-04-07  
/**
	 * 解析URL参数,并返回一个对象
	 */	
	getRequestObject : function(parameters){
		var defaults = {
			url : window.location.href
		};
		jQuery.extend(defaults,parameters);
		var allargs = $.trim(defaults.url) ;
		var ro = {};
		ro.url = allargs.split('?')[0] ;
		ro.ps = allargs.split('?')[1] ;
		//URL参数
		ro.before = $.iamsese.getQueryString(ro.ps.split('#')[0]);
		//锚点参数
		ro.after = $.iamsese.getQueryString(ro.ps.split('#')[1]);		
		//$.iamsese.showAlert(ro);
		allargs = null ;
		return ro ;
	}
0 请登录后投票
   发表时间:2009-04-20  
String.prototype.alert = function(){alert(this.toString())}
"色色".alert();
0 请登录后投票
   发表时间:2009-04-21  
这里面有的方法摘自 FF浏览器组件

/**
 * @file: common.js
 * @author: 色色[vb2005xu]
 * @date: 2009年4月21日9:34:06
 * @description: 
 * 		通用JS文件,里面定义了常用的一些函数
 */


/**
 * Returns true if the specified value is |null|
 */
function isNull(val) {
	return val === null;
}

/**
 * Returns true if the specified value is an array
 */
function isArray(val) {
	return isObject(val) && val.constructor == Array;
}

/**
 * Returns true if the specified value is a string
 */
function isString(val) {
	return typeof val == "string";
}

/**
 * Returns true if the specified value is a boolean
 */
function isBoolean(val) {
	return typeof val == "boolean";
}

/**
 * Returns true if the specified value is a number
 */
function isNumber(val) {
	return typeof val == "number";
}

/**
 * Returns true if the specified value is a function
 */
function isFunction(val) {
	return typeof val == "function";
}

/**
 * Returns true if the specified value is an object
 */
function isObject(val) {
	return val && typeof val == "object";
}

/**
 * Returns an array of all the properties defined on an object
 */
function getObjectProps(obj) {
	var ret = [];

	for (var p in obj) {
		ret.push(p);
	}

	return ret;
}

/**
 * Returns true if the specified value is an object which has no properties
 * defined.
 */
function isEmptyObject(val) {
	if (!isObject(val)) {
		return false;
	}

	for (var p in val) {
		return false;
	}

	return true;
}

var getHashCode;
var removeHashCode;

(function() {
	var hashCodeProperty = "lang_hashCode_";

	/**
	 * Adds a lang_hashCode_ field to an object. The hash code is unique for
	 * the given object.
	 * 
	 * @param obj
	 *            {Object} The object to get the hash code for
	 * @returns {Number} The hash code for the object
	 */
	getHashCode = function(obj) {
		// In IE, DOM nodes do not extend Object so they do not have this
		// method.
		// we need to check hasOwnProperty because the proto might have this
		// set.
		if (obj.hasOwnProperty && obj.hasOwnProperty(hashCodeProperty)) {
			return obj[hashCodeProperty];
		}
		if (!obj[hashCodeProperty]) {
			obj[hashCodeProperty] = ++getHashCode.hashCodeCounter_;
		}
		return obj[hashCodeProperty];
	};

	/**
	 * Removes the lang_hashCode_ field from an object.
	 * 
	 * @param obj
	 *            {Object} The object to remove the field from.
	 */
	removeHashCode = function(obj) {
		obj.removeAttribute(hashCodeProperty);
	};

	getHashCode.hashCodeCounter_ = 0;
})();

/**
 * Fast prefix-checker.
 */
String.prototype.startsWith = function(prefix) {
	if (this.length < prefix.length) {
		return false;
	}

	if (this.substring(0, prefix.length) == prefix) {
		return true;
	}

	return false;
}

/**
 * Removes whitespace from the beginning and end of the string
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

/**
 * Does simple python-style string substitution. "foo%s hot%s".subs("bar",
 * "dog") becomes "foobar hotdot". For more fully-featured templating, see
 * template.js.
 */
String.prototype.subs = function() {
	var ret = this;

	// this appears to be slow, but testing shows it compares more or less
	// equiv.
	// to the regex.exec method.
	for (var i = 0; i < arguments.length; i++) {
		ret = ret.replace(/\%s/, String(arguments[i]));
	}

	return ret;
}


/**
 * Returns the last element on an array without removing it.
 */
Array.prototype.peek = function() {
	return this[this.length - 1];
}

/**
 * Repeat a string -- 2.1的为3 * 
 * @param double number
 * @return str
 * 
 * "1\n".repeat(2.1).alert();
 */
String.prototype.repeat = function(number){
	var str = '' ;
	number = isNumber(number) ? number : 1 ;
	for (var i = 0; i < number; i++) {
		str += this.toString();
	} 
	return str ;
}

/**
 * alert string using debug 
 */
String.prototype.alert = function(){
	alert(this.toString());
}
/**
 * alert array using debug 
 */
Array.prototype.alert = function(){
	
	var arr = this ;
	var array2str = function(arr,tnum){
		//tnum \t的数量
		tnum = isNumber(tnum) ? tnum : 0 ;
		for (var i = 0; i < arr.length; i++) {
			if (isArray(arr[i])) {
			 	//arguments.callee 指代当前函数对象				
				arr[i] = arguments.callee(arr[i],tnum + 1);
			 }
		}
		return	"[" + "\n" +
					"\t".repeat(tnum+1) + 
						arr.join(",\n" + "\t".repeat(tnum+1)).toString() + 				 
				"\n" + "\t".repeat( tnum   ) + "]" ;
			
	};
	array2str(arr).alert();
}

0 请登录后投票
   发表时间:2009-04-21  

    
    /**
	 * 函数命名空间的快速查找
	 */
	this.nsQuickFunc = function(){
		/**
		 * 动态创建函数对象的内部函数
		 */
		function cfn(fn){
			var tpl = 'if (typeof #fn# == "undefined"){#fn# = function(){};}' ;
			tpl = tpl.replace(/#fn#/g,fn);
        	eval(tpl);	
        };		
		var a=arguments ,ns_str=null ,d, fn;		
		
		for (var i=0; i<a.length; ++i) {
			ns_str=arguments[i];
			d=ns_str.split(".");
			fn = d[0]; //fn是函数名称
			cfn(fn);
			for (var j=1; j<d.length; ++j) {
	        	fn += '.prototype.' + d[j] ; 
	        	cfn( fn );
	        }
		}
	};
    

0 请登录后投票
   发表时间:2009-04-21  
/**
 * 定义QUI命名空间
 * 
 * QUI是UCREN的Jquery版本的衍生品
 * 
 */
function QUI(){
	this.version = '1.0' ;
	this.appPath = this.getAppPath();
	
	
	/**
	 * {}对象命名空间 -- 摘自EXT JS
	 * 这个就相当于定义一个包
	 */
	this.ns = function(){
        var a=arguments, o=null, i, j, d, rt;
        for (i=0; i<a.length; ++i) {
            d=a[i].split(".");
            rt = d[0];
            eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
            for (j=1; j<d.length; ++j) {
                o[d[j]]=o[d[j]] || {};
                o=o[d[j]];
            }
        }
    };
    
    /**
     * 定义类方法,如果前面的命名空间不存在则创建之
     */
    this.Class = function(){
    	function cfn(fn){
			var tpl = 'if (typeof #fn# == "undefined"){#fn# = function(){};}' ;
			tpl = tpl.replace(/#fn#/g,fn);
        	eval(tpl);	
        };
        var a=arguments ,ns_str=null ,d, fn;		
		for (var i=0; i<a.length; ++i) {
			ns_str=arguments[i];
			//确保前面的命名空间有效
			d=ns_str.split(".");
			if (d.length === 1)
				cfn(ns_str);
			else {
				var dd = ns_str.replace(d[d.length - 1],''); 
				this.ns(dd);
				cfn(ns_str);
			}
		}
    }
}


QUI.prototype = {
	
	/**
	 * 返回QUI所在的路径 , 用于加载资源文件
	 */ 
	getAppPath: function(){
		var script = document.getElementsByTagName("script");
		for (var i = 0; i < script.length; i++) {
			var match = script[i].src.match(/.*QUI.js($|\?.*)/);
			if (match) {
				return script[i].src.replace(/QUI\.js.*/, '');
			}			
		}
	}
};
var $qui = new QUI();

/**
 * 提供多功能的alert函数
 * 接收 变量,数组,对象,混合对象数组的alert
 */
$qui.Class('Alert');
jQuery.extend(Alert.prototype,{
	
	show: function(){
		var a = arguments[0];
		if (isString(a)){
			a.alert();
		}
		else if (isArray(a))
			a.alert();
		else if (isObject(a))
			Objalert(a);
	}
	
	
});
b = new Alert();
b.show($qui);
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics