接續上一篇,這裡再整理一批實用上很順手的 jQuery 小技巧。這些片段平時想不起來,需要時又特別耗時間查,建議收藏。
$(document).ready(function() {
$('#id').replaceWith(' <DIV>I have been replaced</DIV> ');
});
$(document).ready(function() {
window.setTimeout(function() {
// do something
}, 1000);
});
$(document).ready(function() {
var el = $('#id');
el.html(el.html().replace(/word/ig, ""));
});
用 .length 判斷,這比直接檢查物件本身可靠得多:
$(document).ready(function() {
if ($('#id').length) {
// do something
}
});
$(document).ready(function() {
$("div").click(function(){
//get the url from href attribute and launch the url
window.location=$(this).find("a").attr("href");
return false;
});
// how to use <DIV><A href="index.html">home</A></DIV>
});
$(document).ready(function() {
function checkWindowSize() {
if ( $(window).width() > 1200 ) {
$('body').addClass('large');
} else {
$('body').removeClass('large');
}
}
$(window).resize(checkWindowSize);
});
$(document).ready(function() {
var cloned = $('#id').clone();
// how to use <DIV id=id></DIV>
});
$(document).ready(function() {
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;
}
$("#id").center();
});
注意這裡把 scrollTop/scrollLeft 加了回來,否則頁面捲動後「置中」會變成「相對於視窗頂端」。
$(document).ready(function() {
$.extend($.expr[':'], {
moreThen1000px: function(a) {
return $(a).width() > 1000;
}
});
$('.box:moreThen1000px').click(function() {
// creating a simple js alert box
alert('The element that you have clicked is over 1000 pixels wide');
});
});
$(document).ready(function() {
$("p").size();
});
$(document).ready(function() {
$("ul").addClass("Replaced");
$("ul > li").prepend("‒ ");
// how to use
// ul.Replaced { list-style : none; }
});
//Example 1
<SCRIPT src="https://www.google.com/jsapi"></SCRIPT>
<SCRIPT type=text/javascript>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
// do something
});
</SCRIPT>
<SCRIPT type=text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
// Example 2:(the best and fastest way)
<SCRIPT type=text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
除錯或想確認「沒有動畫時」的版面狀態時很好用:
$(document).ready(function() {
jQuery.fx.off = true;
});
$(document).ready(function() {
var $jq = jQuery.noConflict();
$jq('#id').show();
});
noConflict() 把 $ 的控制權還給其他函式庫(最常見的是 Prototype),之後改用自訂的別名呼叫即可。