Jquery常用的功能

来源:互联网 发布:js arguments递归 编辑:程序博客网 时间:2024/05/16 15:37

1、判断一个元素是否为空
if ($('#id').html()) {
// do something
}

2、替换元素
$('#id').replaceWith('

I have been replaced

');

3、jquery timer 返回函数
$(document).ready(function() {
window.setTimeout(function() {
// do something
}, 1000);
});

4、jquery也玩替换
$(document).ready(function() {
var el= $('#id');
el.html(el.html().replace(/word/ig, ""));
});

5、判断元素是否存在
$(document).ready(function() {
if ($('#id').length) {
// do something
}
});

6、让div也可以click
$("div").click(function(){
//get the url from href attribute and launch the url
window.location=$(this).find("a").attr("href"); return false;
});// how to use

home

7、使用jquery来判断浏览器大小添加不同的class
$(document).ready(function() {
function checkWindowSize() {
if ( $(window).width() > 1200 ) {
$('body').addClass('large');
}
else {
$('body').removeClass('large');
}
}
$(window).resize(checkWindowSize);
});
8、几个字符就clone!
var cloned= $('#id').clone()
9、设置div在屏幕中央
$(document).ready(function() {
jQuery.fn.center= function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
$("#id").center();
});

10、创建自己的选择器
$(document).ready(function() {
$.extend($.expr[':'], {
moreThen1000px: function(a) {
return $(a).width() > 1000;
}
});
$('.box:moreThen1000px').click(function() {
// creating a simple js alert box
alert('The element that you have clicked is over 1000 pixels wide');
});
});

11、计算元素的数目
$(document).ready(function() {
$("p").size();
});

12、设置自己的li样式
$(document).ready(function() {
$("ul").addClass("Replaced");
$("ul > li").prepend("? ");
// how to use
ul.Replaced { list-style : none; }
});

13、使用google的主机来加载jquery库

// Example 2:(the best and fastest way)

14、关闭jquery动画效果
$(document).ready(function() {
jQuery.fx.off= true;
});

15、使用自己的jquery标识
$(document).ready(function() {
var $jq= jQuery.noConflict();
$jq('#id').show();
});

0 0