首页 > 其他分享 >比较实用的jQuery代码段

比较实用的jQuery代码段

时间:2023-03-08 15:31:50浏览次数:39  
标签:jQuery function return 元素 代码段 实用 如何 var


1. 如何检测各种浏览器:
(1)navigator.userAgent返回一个浏览器信息字符串。
(2)用到indexOf()方法,查找字符串中是否有指定的浏览器类型。

if(navigator.userAgent.indexOf("MSIE")>0) {
return "MSIE";
}
if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
return "Firefox";
}
if(isSafari=navigator.userAgent.indexOf("Safari")>0) {
return "Safari";
}
if(isCamino=navigator.userAgent.indexOf("Camino")>0){
return "Camino";
}
if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){
return "Gecko";
}

2. 如何验证某个元素是否为空:


if ($('#keks').html()) {
<span style="white-space:pre"> </span>//非空
}

3. 如何从一个未排序的集合中找出某个元素的索引号


$("ul > li").click(function () {
var index = $(this).prevAll().length;
});

4. 如何使用多个属性来进行过滤


//在使用许多相类似的有着不同类型的input元素时,这种基于精确度的方法很有用
var elements = $('#someid input[type=sometype][value=somevalue]').get();

5. 如何使用jQuery来预加载图像:


jQuery.preloadImages = function() {
$("img[alt=1]").attr('src', arguments[0]);
$("img[alt=2]").attr('src', arguments[1]);
$("img[alt=3]").attr('src', arguments[2]);
};
jQuery(document).ready(function() {
$.preloadImages('1.JPG', '2.JPG', '3.JPG');
})
<img src="" alt="1"/>
<img src="" alt="2"/>
<img src="" alt="3"/>

6. 如何为任何与选择器相匹配的元素设置事件处理程序:


$('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(){
<span style="white-space:pre"> </span>$(this).toggleClass("hover");
});

7. 如何找到一个已经被选中的option元素:


$('#someElement').find('option:selected');

8. 如何隐藏一个包含了某个值文本的元素:


$("p:contains('thetextvalue')").hide();

9. 如何自动滚动到页面中的某区域


jQuery.fn.autoscroll = function(selector) {
$('html,body').animate({scrollTop:$(this.selector).offset().top},500);
}
<span style="font-size:14px;">//然后像这样来滚动到你希望去到的class/area上
<span style="font-size:14px;">$('.area_name').autoscroll();</span></span>

10. 如何替换串中的词


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

"abacacf".replace('a','9') //第一个运行的结果 9bacaf 这个只是替换了第一个
"abacacf".replace(/a/g,'9') //第二个运行的结果 9b9c9f 这个能实现js的全部替换功能

11. 如何禁用右键单击上下文菜单:


$(document).bind('contextmenu',function(e){
return false;
});

12. 如何使用jQuery来检测右键和左键的鼠标单击两种情况:


$("#someelement").bind('mousedown', function(e) {
if( (navigator.userAgent.indexOf("MSIE")==-1 && e.button == 0) || (navigator.userAgent.indexOf("MSIE")>0 && e.button == 1) ) {
alert("Left Mouse Button Clicked");
} else if(e.button == 2) {
alert("Right Mouse Button Clicked");
}
});

13. 如何在一段时间之后自动隐藏或关闭元素(支持1.4版本):


//这是1.3.2中我们使用setTimeout来实现的方式
setTimeout(function() {
$('.mydiv').hide('blind', {}, 500)
}, 5000);
//而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠)
$(".mydiv").delay(5000).hide('blind', {}, 500);

14. 如何限制"Text-Area"域中的字符的个数:


jQuery.fn.maxLength = function(max){
this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type? this.type.toLowerCase() : null;
if(type == "input" && inputType == "text" || inputType == "password"){
//Apply the standard maxLength
this.maxLength = max;
}else if(type == "textarea"){
this.onkeypress = function(e){
var ob = e || event;
var keyCode = ob.keyCode;
var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup = function(){
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
};
}
});
};
//用法
$('#mytextarea').maxLength(500);

15. 在jQuery中如何测试某个元素是否可见


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

16. 如何把一个元素放在屏幕的中心位置:


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;
};
//这样来使用上面的函数:
$(element).center();

17. 如何从元素中除去HTML


(function($) {
$.fn.stripHtml = function() {
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
this.each(function() {
$(this).html( $(this).html().replace(regexp,"") );
});
return $(this);
}
})(jQuery);
//用法:
<p value="123"><b>123</b></p>
<p>456</p>
$('p').stripHtml();
//结果:
<p value="123">123</p>
<p>456</p>

18. 如何使用closest来取得父元素:


closest() 方法获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。


$('#searchBox').closest('div');

19. 如何强制在弹出窗口中打开链接:


jQuery('a.popup').live('click', function(){
newwindow=window.open($(this).attr('href'),",'height=200,width=150′);
if (window.focus) {
newwindow.focus();
}
return false;
});

20. 如何强制在新的选项卡中打开链接:


jQuery('a.newTab').live('click', function(){
newwindow=window.open($(this).href);
jQuery(this).target = "_blank";
return false;
});

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


// 不这样做
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
//替代做法是
$('#nav li').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});

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


$(document).ready(function() {
$(document).mousemove(function(e){
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});

23. 如何把整个的列表元素(List Element,LI)变成可点击的


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


<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>

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


$('#theImage').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});

25. 如何检查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
}

26. 如何让cookie过期:


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



标签:jQuery,function,return,元素,代码段,实用,如何,var
From: https://blog.51cto.com/u_15998238/6108240

相关文章