当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery 常见小例汇总

jQuery 常见小例汇总

2019年04月05日  | 移动技术网IT编程  | 我要评论

1

//这段代码展示了在用户未输入值时,
//如何在文本类型的input域中保留
//一个默认值
wap_val = [];
$(".swap").each(function(i){
wap_val[i] = $(this).val();
$(this).focusin(function(){
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}});});

2

var el = $('#id');
el.html(el.html().replace(/word/ig, ''));

3

$('button.someclass').live('click', somefunction);
//注意,在jquery 1.4.2中,delegate和undelegate选项
//被引入代替live,因为它们提供了更好的上下文支持
//例如,就table来说,以前你会用
//.live()
$("table").each(function(){
$("td", this).live("hover", function(){
$(this).toggleclass("hover");
});
});
//现在用
$("table").delegate("td", "hover", function(){
$(this).toggleclass("hover");
});

4.如何把已创建的元素动态地添加到dom中:

var newdiv = $(''); 
  newdiv.attr('id','mynewdiv').appendto('body'); 

5

var cloned = $('#somediv').clone();

6

if($(element).is(':visible') == 'true') { 
  //该元素是可见的 
} 

7.jq中定位

jquery.fn.center = function () { 
  this.css('position','absolute'); 
  this.css('top', ( $(window).height() - this.height() ) / +$(window).scrolltop() + 'px'); 
  this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollleft() + 'px'); 
  return this; 
} 
//这样来使用上面的函数: 
$(element).center(); 

8.如何把有着某个特定名称的所有元素的值都放到一个数组中:

var arrinputvalues = new array();
$("input[name='table[]']").each(function(){
arrinputvalues.push($(this).val());
});

9.在jquery中如何使用.siblings()来选择同辈元素

$('#nav li').click(function(){
$('#nav li').removeclass('active');
$(this).addclass('active');
});
//替代做法是
$('#nav li').click(function(){
$(this).addclass('active').siblings().removeclass('active');
});

10.正反选

var tog = false; 
$('a').click(function() { 
  $("input[type=checkbox]").attr("checked",!tog); 
  tog = !tog; 
}); 

11.如何获得鼠标垫光标位置x和y

$(document).ready(function() {
$(document).mousemove(function(e){
$('#xy').html(”x axis : ” + e.pagex + ” | y axis ” + e.pagey);
});
});

12.如何把整个的列表元素(list element,li)变成可点击的

$("ul li").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});

13.如何检查图像是否已经被完全加载进来

$('#theimage').attr('src', 'image.jpg').load(function() {
alert('this image has been loaded');
});

14.如何检查cookie是否启用

var dt = new date();
dt.setseconds(dt.getseconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.togmtstring();
var cookiesenabled = document.cookie.indexof("cookietest=") != -1;
if(!cookiesenabled) {
//没有启用cookie
}

15.如何让cookie过期:

var date = new date();
date.settime(date.gettime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网