1. jQuery常用dom操作
(1) 用$函数,比原生写法更简洁
- 原生: document.querySelectorAll(“.list .item”).forEach((item) => (item.style.color = “red”));
- jquery: $(“.item”, “.list”).css(“color”, “red”);
<ul class="list">
<li class="li item">item1</li>
<li class="li item">item2</li>
<li class="li item">item3</li>
</ul>
(2) 将原生js对象转换jQuery对象
$(document.body).css(“background-color”,”blue”);
(3) $(html文本): 创建dom元素,直接包装成jQuery对象返回
document.body.insertAdjacentHTML(“afterbegin”,”<p> let’s write more code</p>“);
$(“<p>let’s write more code</p>“).insertAfter(“.list”);
(4) $(回调): dom树一旦创建完成,就会立即执行这个回调
<script>
$(() => {
$(“body h2”).css(“color”, “red”);
});
</script>
<h2>have fun on the code writing</h2>