一些实用的jQuery代码片段收集

2020-05-16 18:46:48易采站长站整理

下边这些jQuery片段只是很少的一部分,如果您在学习过程中也遇到过一些常用的jQuery代码,欢迎分享。下边就让我们看看这些有代码片段。
1.jQuery得到用户IP:

$.getJSON(“http://jsonip.appspot.com?callback=?”, function (data) {
alert(“Your ip: ” + data.ip);
});

2.jQuery查看图片的宽度和高度:

var theImage = new Image();
theImage.src = $(‘#imageid’).attr(“src”);
alert(“Width: ” + theImage.width);
alert(“Height: ” + theImage.height);

3.jQuery查找指定字符串:

var str = $(‘*:contains(“the string”)’);
4.js 判断浏览器是否启用cookie:
$(document).ready(function () {
document.cookie = “cookieid=1; expires=60”;
var result = document.cookie.indexOf(“cookieid=”) != -1;
if (!result) {
alert(“浏览器未启用cookie”);
}
});

5.jQuery检测键盘按键:

$(document).ready(function () {
$(this).keypress(function (e) {
switch (e.which) {
case 13:
alert(“您按下了回车键”);
break;
//more detect
}
});
});

好了,本篇就小结到这里,希望本篇jQuery代码片段文章能对大家起到帮助作用
1.jQuery 滚动到顶部/底部
关于jQuery滚动,本站在之前已经发过类似文章,如:jQuery 回到顶部,下边将它们再次整理一下:

//滚动到顶部
$(“html, body”).animate({ scrollTop: “0px” }, 1000);
//滚动到底部
//$(“#container”):要滚动的元素
$(“html, body”).animate({
scrollTop: $(“#container”).height()
}, 1000);

2.jQuery 判断元素是否存在
怎么使用 jQuery 判断元素是否存在,相信不少 jQuery 学习者都会问这个问题,方法很简单,如下:

if ($(” #elementid”).length) {
//元素存在
}

3.使用 abort() 方法取消 Ajax 请求
使用 abort() 方法在执行 js 异步请求的时候可以取消上一次的请求,方法如下:

var req = $.ajax({
type: “post”,
url: “/article/form/comment.aspx”,
data: { “id”: 1 },
success: function() {
//handle
}
});
//取消 Ajax 请求
if (req) {
req.abort()
}

jQuery Ajax 是使用 jQuery 比较重要的一块,如果你是 jQuery 初学者,可能会对上边的代码感觉到陌生,或许你可以看看 jQuery学习大总结(五)jQuery Ajax 。
4.jQuery 禁用鼠标右键

$(document).ready(function() {
$(document).bind(“contextmenu”, function() {
return false;
});
});

5.向由setTimeout()调用的方法中传参