jquery 几个实用的小方法
1、将文本框内的光标放在最后
function cursor_to_end(id)
{
var txt_focus = document.getElementById(id);
var txt_len = $("#"+id).val().length;
{
var range = txt_focus.createTextRange();
range.move("character", txt_len);
range.select();
}
else
{
var obj = $("#"+id).get(0);
var num = $("#"+id).val().length;
obj.setSelectionRange(num, num);
obj.focus();
}
}
2、判断数组中是否存在某元素
function in_array(arr, val)
{
for(v in arr)
{
if(arr[v] == val)
{
return true;
}
}
return false;
}
3、设置cookie
function setCookie(name,value,expireHours){
var cookieString=name+"="+escape(value);
//判断是否设置过期时间
if(expireHours>0){
var date=new Date();
date.setTime(date.getTime+expireHours*3600*1000);
cookieString=cookieString+"; expire="+date.toGMTString();
}
document.cookie=cookieString;
}
function setCookie(key, value, path)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + 2592000);
var cookie_str = key + "=" + escape(value) + ";expires=" + exdate.toGMTString();
if(path){
cookie_str += ";path=" + path;
}
var cookie_domain = getDomain();
cookie_str += ";domain=" + cookie_domain;
document.cookie = cookie_str;
}
4、获取cookie
function getCookie(name){
var strCookie=document.cookie;
var arrCookie=strCookie.split("; ");
for(var i=0;i<arrCookie.length;i++){
var arr=arrCookie[i].split("=");
if(arr[0]==name)return arr[1];
}
return null;
}
5、获取域名
function getDomain()
{
var arr = document.domain.split('.');
var str = '';
if(arr.length == 2)
{
str = arr[0] + '.' + arr[1];
}
else
{
str = arr[1] + '.' + arr[2];
}
return str;
}
6、截取字符串
function cut_string(str,leng)
{
var cut_str = '';
var len = 0;
for (var i=0; i<str.length; i++)
{
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))//single byte character
{
len+=0.5;
}
else
{
len++;
}
cut_str += str.charAt(i);
if (parseInt(len) > leng)
{
return cut_str + '...';
}
}
return str;
}