jQuery操作DOM常用的方法和Ajax应用
一、jQuery操作DOM
1.1 添加元素
1.1.1 appendTo
在被选择的元素尾部插入指定的内容。
- 语法
$(context).appendTo(selector);
- 案例
$('<h2>祝大家春节快乐!</h2>').appendTo(document.body);
- 效果图
1.1.2 与appendTo
作用一样的还有一个append
,该方法是在被选择的元素结尾添加指定的内容,注意添加的内容还是在被选择的元素内部。
- 语法
$(selector).append(content)
- 案例
$('body').append('<h2>Hello World!</h2>');
- 效果图
同时,append
方法的参数还可以传一个函数,具体使用方法请看下面的案例:
const ol = $('body').append('<ol></ol>');
$('ol').append(() => {
let str = '';
for (let i = 0; i < 5; i++) {
str += `<li>新品上市${i+1}</li>`;
}
return str;
});
- 效果图
以上两个方法,还有一个简化记忆的方法:
- 子元素.appendTo(父元素)
- 父元素.append(子元素)
二、jQuery种的AJAX请求
2.1 $.get()请求
<button>1. $.get()请求数据</button>
<script>
$("button:first-of-type").click(function (ev) {
console.log(ev);
// users.php?id=1 查询字符串方式,还可以用对象的方式:
// get("users.php", {id: 1}, function (data) {});
$.get("users.php", {id: 2}, function (data) {
console.log(data);
$(ev.target).after("<div></div>").next().html(data);
});
});
</script>
2.2 $.post()请求
<button>2. $.post()请求数据</button>
<script>
$("button:nth-of-type(2)").click(function (ev) {
console.log(ev);
$.post("users.php", {id: 3}, function (data) {
console.log(data);
$(ev.target).after("<div></div>").next().html(data);
})
});
</script>
2.3 $.ajax()请求
<button>3. $.ajax()JSONP跨域请求数据</button>
<script>
$("button:last-of-type").click(function (ev) {
$.ajax({
type: "get",
url: "http://localhost:9999/index.php?id=2",
dataType: "jsonp",
// 告诉跨域访问的服务器需要返回的函数名称
// 在一个 jsonp 中重写回调函数的字符串。相当于用jsonp替换掉默认的callback
jsonp: "jsonp",
// 在一个 jsonp 中规定回调函数的名称。
jsonpCallback: "jsonp",
success: function (data) {
console.log(data);
$("button:last-of-type").after("<div>").next().html(`${data.name}:${data.email}`);
},
});
});
</script>
三、使用jQuery写一个留言板(ToDoList)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>留言板</title>
<!-- <link rel="stylesheet" href="message.css"> -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
* {
margin: 0;
padding: 0;
font-size: 10px;
box-sizing: border-box;
font-family: Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial, sans-serif;
}
ul,
li {
list-style: none;
}
.box {
width: 50rem;
height: 10rem;
margin: 1rem auto;
}
h2 {
font-size: 3rem;
display: flex;
justify-content: center;
margin-bottom: 1rem;
}
#message {
display: flex;
flex-flow: column nowrap;
width: 100%;
}
#message textarea {
width: 100%;
min-height: 10rem;
padding: .6rem 1rem;
border: 1px solid #c9c9c9;
border-radius: 2px;
outline: none;
font-size: 1.4rem;
font-family: inherit;
}
#message .button {
width: 100%;
height: 5rem;
margin-top: 1rem;
}
#message .button .btn {
padding: 0 2rem;
height: 3.8rem;
border-radius: 3px;
border-width: 0;
font-size: 1.2rem;
outline: none;
cursor: pointer;
}
#message .button .btn:hover {
transition: all .3s;
opacity: .8;
}
#message .button .btn.btn-submit {
background-color: #3e7771;
color: #ffffff;
}
#message .button .btn.btn-rest {
margin-left: .5rem;
}
#message .content-wrap em.tips {
font-style: normal;
color: red;
margin-top: 1rem;
}
#list {
width: 100%;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: auto;
margin-top: 1rem;
}
#list li {
display: grid;
grid-template-columns: 4rem 1fr;
grid-template-rows: auto auto;
gap: .5rem;
margin-top: 1rem;
}
#list li.item .avatar {
width: 4rem;
height: 4rem;
}
#list li.item .avatar img {
width: 100%;
height: 100%;
border-radius: 50%;
}
#list li.item .comment {
display: grid;
grid-template-columns: 1fr;
row-gap: .5rem;
}
#list li.item .comment .title {
display: flex;
flex: rows nowrap;
align-items: center;
}
#list li.item .comment .title .nick>* {
font-size: 1.6rem;
color: #000000;
}
#list li.item .comment .title .time {
color: #8c92a4;
margin-left: .5rem;
font-size: 1.2rem;
color: #8c92a4;
font-size: 1.4rem;
}
#list li.item .comment .context {
color: #8c92a4;
font-size: 1.2rem;
color: #40485B;
font-size: 1.4rem;
margin: .5rem 0;
}
#list li.item .del {
margin: .5rem 0;
display: grid;
cursor: pointer;
border: none;
place-self: center end;
grid-area: 2 / 1 / 2 / 3;
padding: .5rem;
outline: none;
}
hr {
border-color: rgba(222, 222, 222, .5);
}
</style>
</head>
<body>
<div class="box">
<h2>留言板</h2>
<div id="message">
<div class="content-wrap">
<textarea class="content" name="message" value="111" placeholder="请输入内容"></textarea>
<em class="tips" style="display: none;">* 留言内容不能为空!</em>
</div>
<div class="button">
<button class="btn btn-submit">立即提交</button>
<button type="reset" class="btn btn-reset">重置</input>
</div>
</div>
<hr>
<ul id="list">
</ul>
</div>
<script>
$(".btn-submit").click(function (ev) {
let msg = $(".content").val();
console.log(ev.target);
if (msg === "") {
$(".tips").css("display", "block");
return false;
}
// 文本结构
let str = ` <li class="item" >
<div class="avatar">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAHCklEQVRoQ+2Zd1BUVxTGv106K82VJk1BEHAElGBBYxR1Eomxm6gJjo4tGnUsmZiIRkfDRMeWaOwmxthLNBg10dhFUBEZEASRLkVAWFjaUpbNnOvsm0VBGN9j3MG9f8Huffed3/nuPeWuqPvpaSq8Q0OkA27nausUbucCQ6ewTuF25gHdlm5ngr6Co1NYp3A784BuS7czQbUnaHXpYIcprkGwMJDgiTwX+55cYMYNtvNFTmURUsvz2sT3b21L97P2wnr/WbA1scKj0iyMu7YaS3tMRIjbMKTIc7A85tc2geYNPNZ5IMj41o4ChQybE0+xZ9TApObIy6FY5z8Tnzj1h1gkwkNZRptA8wb+ofd0THAZ1FpephrBNQVMi2hCPy7LwdfRuwRVmjfwSt8vMMZ5AAdsINaHoVgfKqigUNaiQdX4Bim9PB8Tr69h888NC0M3s86cE+gzib4xVvtNRbBjX6h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9orBL0fqpNJsFrmdJNZsblltJX5JDsfBtP94w9ICvBSmBca7vI+ATt3xbcy+RgYt6zkJIa7DoCcWg6KrZiDTnKhZf1NgM9EzYqqyY1Gej3UPjyKiIEEQWEGAm7KEtjo1ETbGlkwhau/O59xt0ujeUndseG82HEw7cd9TirqUF4MNCcdZ17XKbyp8rVxxIO0SwrMjecHzVvjlt1Nrt63vAvS3eXEL8m9uNBbfezV3UiMxuWsQ/KXurBJTj6eVReysnsq6yX2mDmzZlYWYHbmFRfE3HYIDL/Yej2ndPnxRL1cVYWn0bu7sUjCiqDvCoQ/sTTs2mY8zKp5hbtTPHFRPq64sTtAOiC1JxeQbYW/Kyp4TFHhS1yFY0mMCzA1MWY6lQEbl5CjnQNA2dzOz53Kw2mrqhSnHelm4wNPCCfUNShxMv4z1D4+xKXRnFuo7BaZ6xlz5yYdYMGAqEFb6hrCUQsXH30+jWCDTTF1qQykgFSvkCH8ayaIvndPZHh9jnucoUPMhr6tiF33HMq5hU8CXrFKj1BQWd4TV03yGIMAEtabXNAZLMFGFSVhwdxtXT6sbC1I9qSwbZ7Ii2F2V5tA8+9RhUV7OrSqGg6mURe5UeS4+u/ED756YN7CmsgRADTulIM2LdJrjKLHGxdxopmZzQ9NxmnNom+9PvYhNiSf5iCvMGSYYyrlUYFC1FRZ/hFcJSNDf+UxmxQwpTTuGys2Fd7fzVlewoEXV1XT3j1hzIES9S4ZRX0wXenSXpb7N5C2v0FFaCIPaeg3eZ7itDRR6fR2w0B7VtvV0CmubIkLbo1NYaI9q23o6hbVNEaHt0SkstEe1bT2dwtqmiND26BQW2qPatt47p/D/fz1ommzIsNIAAAAASUVORK5CYII=" />
</div>
<div class="comment">
<div class="title">
<span class="nick"><b>残破的蛋蛋</b></span>
<div class="time">${formatDate(Date.now())}</div>
</div>
<div class="context">${msg}</div>
<hr>
</div>
<button class="del" onclick="del(this)">删除</button>
</li>
`;
$("#list").prepend(str);
});
// 删除元素
function del (element) {
console.log(element.parentNode);
// console.log(this);
if (confirm("确认删除这条评论吗?")) {
element.parentNode.outerHTML = null;
}
}
// 重置内容
$(".btn-reset").click(function (ev) {
console.log(ev.currentTarget);
$(".content").val(null);
});
// 获取时间
function formatDate(time) {
let date = new Date(time);
console.log(date);
let y = date.getFullYear();
console.log(y);
let m = date.getMonth();
m = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
console.log(m);
let d = date.getDate();
console.log(d);
let h = date.getHours();
console.log(h);
let i = date.getMinutes();
console.log(i);
let s = date.getSeconds();
console.log(s);
return `${y}-${m}-${d} ${h}-${i}-${s}`;
}
</script>
</body>
</html>
- 效果图: