以下整理一些常見且實用的 jQuery 小片段,適合日常開發時快速查閱。
$.getJSON('https://jsonip.appspot.com?callback=?', function (data) {
alert('Your ip: ' + data.ip);
});
var theImage = new Image();
theImage.src = $('#imageid').attr('src');
alert('Width: ' + theImage.width);
alert('Height: ' + theImage.height);
if ($('#elementid').length) {
// 元素存在
}
var req = $.ajax({
type: 'post',
url: '/article/form/comment.aspx',
data: { id: 1 },
success: function () {
// 處理成功
}
});
if (req) {
req.abort();
}
$('html, body').animate({ scrollTop: '0px' }, 1000);
$('html, body').animate({
scrollTop: $('#container').height()
}, 1000);
這些片段涵蓋了元素判斷、視覺效果、網路請求與滾動操作,都是前端開發中很常遇到的情境。