Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
attr()
方法:获取/设置元素属性需先引入JQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
html
<form action="index.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
attr(name)
:getter 获取元素属性例如获取表单属性
const form=$("form");
console.log(form.attr("action"));//index.php
attr(name,value)
:setter 设置元素属性例如设置表单属性
const form=$("form");
form.attr("action","admin/index.php");
console.log(form.attr("action"));//admin/index.php
第二个参数可以使用回调函数
form.attr("action",()=>{
let method=form.attr("method").toUpperCase();
return method==="GET"?"index.php?username=Jy":"admin/index.php";
});
console.log(form.attr("action"));//如果为get则返回index.php?username=Jy;post则返回admin/index.php
css()
:获取/设置元素的行内样式需先引入JQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
css
<style>
form{
width: 100px;
}
input{
width: 95%;
}
</style>
html
<form action="index.php" method="POST">
帐号: <input type="text" name="username" />
密码:<input type="password" name="password" />
</form>
css(name)
:getter 获取元素行内样式例如获取表单宽度
const form=$("form");
console.log(form.css("width"));//100px
使用原生style只能获取style上的行内样式
console.log(document.querySelector("form").style.width);//无法获取
css样式表里的样式必须使用计算样式才可以获取
console.log(window.getComputedStyle(document.querySelector("form"),null).getPropertyValue("width"));//100px
css(name,value)
:setter 设置元素行内样式例如设置表单边框;多个参数用{}包裹,并用,隔开即可
const form=$("form");
form.css("border","2px solid red");//边框变为红色;
第二个参数可以使用回调函数
form.css("color",()=>{
const colors=["red","blue","yellow"];
let i=Math.floor(Math.random() * colors.length);//Math.floor:向下取整;Math.random:0-1之间随机取值
return colors[i];
});
//字体颜色将随机更换
val()
:设置/获取表单控件的value属性需先引入JQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
html
<form action="index.php" method="get">
帐号:<input type="text" name="username" value="Jy" />
密码:<input type="password" name="password" value="123456" />
性别:
<label for="man">男</label>
<input type="radio" name="sex" id="man" value="1" />
<label for="woman">女</label>
<input type="radio" name="sex" id="woman" value="0" checked/>
</form>
<script>
console.log($("input[name='username']").val());//Jy
console.log($("input:password").val());//123456
console.log($("input:radio:checked").val());//0
$("input[name='username']").val("Jy2");//账号的值变为Jy2
</script>
html()
等同与innerHTML、text()
等同于innerText/textContent