jquery 常用小功能收集
--> -->
在新窗口打开链接
$(document).ready(function() {
//全部链接新页面打开
$('a[href^="http://"]').attr("target", "_blank");
//部分链接新页面打开,比如class='menu'的链接
$('a[class='menu']').click(function(){
this.target = "_blank";
});
});
<a href="http://www.opensourcehunter.com" calss='menu'>新窗口打开</a>
右键禁止点击
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
图像预加载
$(document).ready(function() {
jQuery.preloadImages = function()
{
for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);
}
}
//如何使用
$.preloadImages("image1.jpg");
});
返回页面顶部
$(document).ready(function() {
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body')
.animate({scrollTop: targetOffset}, 900);
return false;
}
}
});
// 如何使用
// 此A链接为你想定位的地方
<A name=top></A>
// 返回顶部的链接
<A href="#top">go to top</A>
});
判断某个原始是否为空
$(document).ready(function() {
if ($('#id').html()) {
// 元素为空
}
});
替换某个元素
$(document).ready(function() {
//被替换元素ID
$('#id').replaceWith('
<DIV>准备替换的元素html</DIV>');
});
让整个DIV可点击
$(document).ready(function() {
$("div").click(function(){
//从a链接中获取url
window.location=$(this).find("a").attr("href"); return false;
});
// 如何使用
<DIV><A href="index.html">home</A></DIV>
});
禁止使用jquery动画
$(document).ready(function() {
jQuery.fx.off = true;
});
jquery检查浏览器
$(document).ready(function() {
// Firefox 2
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// do something
}
//Safari
if( $.browser.safari ){
// do something
}
//Chrome
if( $.browser.chrome){
// do something
}
//Camino
if( $.browser.camino){
// do something
}
//Opera
if( $.browser.opera){
// do something
}
//IE6及以下版本
if ($.browser.msie && $.browser.version <= 6 ){
// do something
}
//IE6以上版本
if ($.browser.msie && $.browser.version > 6){
// do something
}
});
解决jquery与其他类库的冲突
$(document).ready(function() {
var $jquery = jQuery.noConflict();
$jquery('#id').show();
});