THAM KHẢO NHANH JQUERY
Selectors, DOM, events, AJAX, effects, traversal
Selectors
Selectors Cơ Bản
$("p") // all
elements
$(".btn") // class selector
$("#main") // ID selector
$("ul > li") // direct children
$("input[type='text']") // attribute selector
Selectors Phổ Biến
| $('*') | Tất cả phần tử |
| $('a, span') | Nhiều selectors |
| $(':first') | Phần tử khớp đầu tiên |
| $(':last') | Phần tử khớp cuối cùng |
| $(':even') / $(':odd') | Phần tử chỉ số chẵn/lẻ |
| $(':visible') / $(':hidden') | Bộ lọc khả năng hiển thị |
| $(':contains(text)') | Phần tử chứa văn bản |
| $(':has(selector)') | Phần tử chứa selector khớp |
Thao Tác DOM
Nội Dung & Cấu Trúc
$("#el").html("Bold"); // set inner HTML
$("#el").text("Plain text"); // set text content
$("ul").append("
New"); // add at end
$("ul").prepend("First"); // add at start
Chèn & Xóa
$("
Hello
").insertAfter("
#el"); // insert after
$("
Hi
").insertBefore("
#el"); // insert before
$("
#el").remove(); // remove element from DOM
$("
#el").empty(); // remove all children
Methods
| .html() | Lấy/thiết lập HTML bên trong |
| .text() | Lấy/thiết lập nội dung văn bản |
| .append() / .prepend() | Thêm con vào cuối/đầu |
| .after() / .before() | Chèn anh em sau/trước |
| .wrap() | Bao phần tử bằng cha mới |
| .clone() | Sao chép sâu phần tử |
| .replaceWith() | Thay thế phần tử |
Events
Gắn Events
$(".btn").on("click", function () {
$(this).toggleClass("active");
});
$(document).on("click", ".dynamic", handler); // delegation
$(".btn").off("click"); // remove handler
Methods Shorthand
| .click(fn) | Handler click |
| .hover(fnIn, fnOut) | Chuột vào/ra |
| .focus() / .blur() | Focus được/mất |
| .change(fn) | Giá trị thay đổi (input/select) |
| .submit(fn) | Gửi form |
| .keydown() / .keyup() | Sự kiện bàn phím |
Document Ready
$(document).ready(function () { /* DOM loaded */ });
$(function () { /* shorthand */ });
Hiệu Ứng & Animation
Hiển Thị / Ẩn / Chuyển Đổi
$("#el").hide(400); // hide with animation
$("#el").show(400); // show with animation
$("#el").toggle(); // toggle visibility
$("#el").fadeIn(600); // fade in
$("#el").slideDown(400); // slide down
Animation Tùy Chỉnh
$("#el").animate({
opacity: 0.5,
left: "+=50px",
height: "toggle"
}, 1000, function () { /* complete */ });
Effect Methods
| .fadeIn() / .fadeOut() | Animate opacity |
| .fadeToggle() | Chuyển đổi với fade |
| .slideDown() / .slideUp() | Animate chiều cao |
| .animate(props, ms) | Animation CSS tùy chỉnh |
| .stop() | Dừng animation hiện tại |
| .delay(ms) | Trì hoãn hiệu ứng tiếp theo trong hàng đợi |
AJAX
Methods Shorthand
$.get("/api/data", function (data) { console.log(data); });
$.post("/api/data", { name: "Alice" }, function (res) {});
$.getJSON("/api/items", function (json) {});
$("#el").load("/fragment.html"); // load HTML into element
$.ajax Đầy Đủ
$.ajax({
url: "/api/data",
method: "POST",
data: JSON.stringify({ key: "val" }),
contentType: "application/json",
success: (res) => console.log(res),
error: (xhr) => console.error(xhr.status)
});
Tùy Chọn AJAX
| url | URL request |
| method | Phương thức HTTP (GET, POST, ...) |
| data | Dữ liệu cần gửi |
| dataType | Loại response mong đợi |
| contentType | Content type của request |
| success / error | Hàm callback |
| headers | Headers request tùy chỉnh |
Traversal
Điều Hướng Cây
$("li").parent(); // direct parent
$("li").parents("ul"); // all matching ancestors
$("ul").children("li"); // direct children
$("ul").find(".active"); // all matching descendants
$("li").siblings(); // sibling elements
Traversal Methods
| .parent() / .parents() | Cha trực tiếp / tất cả tổ tiên |
| .children() / .find() | Con trực tiếp / tất cả con cháu |
| .siblings() | Tất cả phần tử anh em |
| .next() / .prev() | Anh em tiếp theo/trước |
| .closest(sel) | Tổ tiên gần nhất khớp selector |
| .first() / .last() | Đầu/cuối trong tập khớp |
| .eq(index) | Phần tử tại index |
| .filter(sel) | Thu hẹp về phần tử khớp |
Attributes & CSS
Attributes
$("img").attr("src"); // get attribute
$("img").attr("src", "new.jpg"); // set attribute
$("img").removeAttr("title"); // remove attribute
$("input").prop("checked", true); // set property
CSS & Classes
$(".box").css("color", "red"); // set single style
$(".box").css({ color: "red", fontSize: "14px" }); // multi
$("p").addClass("highlight");
$("p").removeClass("highlight");
$("p").toggleClass("active");
$("p").hasClass("active"); // returns boolean
Forms
Giá Trị & Serialize
$("input").val(); // get value
$("input").val("new value"); // set value
$("form").serialize(); // "name=Alice&age=30"
$("form").serializeArray(); // [{name, value}, ...]
Form Selectors
| $(":input") | Tất cả phần tử form |
| $(":checked") | Checkbox/radio đã chọn |
| $(":selected") | Phần tử option đã chọn |
| $(":disabled") | Phần tử bị vô hiệu hóa |
| $(":text") | Input văn bản |
Utilities
Helpers Mảng & Object
$.each([1, 2, 3], function (i, val) { /* iterate */ });
$.each(obj, function (key, val) { /* iterate object */ });
$.extend({}, defaults, options); // merge objects
$.inArray("b", ["a", "b", "c"]); // returns 1 (index)
Utility Methods
| $.each(arr, fn) | Lặp qua mảng hoặc object |
| $.extend(target, ...) | Merge objects (nông) |
| $.inArray(val, arr) | Index của giá trị (-1 nếu không có) |
| $.isArray(obj) | Kiểm tra có phải mảng không |
| $.trim(str) | Xóa khoảng trắng đầu/cuối |
| $.parseJSON(str) | Phân tích chuỗi JSON |
| $.map(arr, fn) | Biến đổi phần tử mảng |
Mẫu Phổ Biến
Chaining
$("ul")
.find("li")
.addClass("item")
.first()
.css("font-weight", "bold");
Mẫu Plugin
$.fn.highlight = function (color) {
return this.each(function () {
$(this).css("background", color || "yellow");
});
};
$("p").highlight("pink");
Giải Quyết Xung Đột
// Avoid $ conflicts with other libraries
jQuery.noConflict();
jQuery(document).ready(function ($) {
$(".btn").click(handler); // $ safe inside
});