Home >Web Front-end >JS Tutorial >Introduction to the basic usage of jQuery objects
jQuery is a lightweight JavaScript library that is widely used in web development. It encapsulates many common DOM operations and event handling methods, greatly simplifying JavaScript programming. complexity. This article will introduce the basic usage of jQuery objects, including how to use jQuery selectors, operate DOM elements, handle events, etc., and use specific code examples to help readers better understand and master the basic knowledge of jQuery.
First, introduce the jQuery library into the HTML document. You can download the jQuery file and introduce it into the page, or you can use CDN to introduce it:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
You can select DOM elements on the page through jQuery selectors. Commonly used selectors include the following:
$("div")
$(".classname")
$("#id")
$("[attrName='attrValue']")
Sample code:
// 选取所有p元素 $("p").css("color", "red"); // 选取class为content的元素 $(".content").hide(); // 选取id为header的元素 $("#header").show(); // 选取属性data-id为1的元素 $("[data-id='1']").addClass("selected");
jQuery provides a wealth of methods to manipulate DOM elements, including addition, deletion, modification, and search operations:
append()
, prepend()
, after()
, before()
remove()
, empty()
attr()
, prop()
, css()
text()
, html()
, val()
Sample code:
// 在p元素后添加一个span元素 $("p").after("<span>这是新增的内容</span>"); // 删除class为content的元素 $(".content").remove(); // 修改id为header的元素的背景色 $("#header").css("background-color", "#f5f5f5"); // 获取输入框的值 var inputValue = $("input").val();
jQuery provides convenient event processing methods that can easily add, remove and trigger events:
on()
off()
trigger()
Sample code:
// 点击按钮时弹出提示框 $("#btn").on("click", function() { alert("按钮被点击了!"); }); // 移除按钮的点击事件处理程序 $("#btn").off("click");
jQuery also provides rich animation effects, which can achieve smooth transition of elements :
show()
, hide()
, toggle()
fadeIn()
, fadeOut()
, fadeToggle()
slideDown()
, slideUp()
, slideToggle()
animate()
Sample code :
// 点击按钮时展示隐藏的内容 $("#toggleBtn").on("click", function() { $("#content").slideToggle(); }); // 自定义动画效果 $("#box").animate({ left: '250px', opacity: '0.5', height: '150px', width: '150px' }, 1000);
Through the introduction of this article, readers can understand the basic usage of jQuery objects, including selecting elements with selectors, operating DOM elements, handling events, and implementing animation effects. Mastering these basic knowledge can help developers use the jQuery library for web development more efficiently. I hope this article can be helpful to beginners and inspire more learning and exploration of jQuery.
The above is the detailed content of Introduction to the basic usage of jQuery objects. For more information, please follow other related articles on the PHP Chinese website!