批改状态:合格
老师批语:
$()函数支持四个参数类型,如下:
公共代码:
<ul id="first"><li>item1</li><li>item2</li><li>item3</li></ul><ul id="second"><li>item1</li><li>item2</li><li>item3</li></ul>
(1) $(选择器,上下文)
//$()传入选择器,选择第一个id为first的ul,然后设置字体颜色为绿色$("#first li").css("color","green");
(2) $(js对象)
//原生对象为html的body,设置背景颜色为黄色$(document.body).css("background","yellow");
(3) $(html文本): 生成dom元素
$("<li>item5</li>").appendTo(document.querySelector("#first"));
(4) $(callback回调函数)
//如果是在 ul.first 代码之前,写$("<li>大象吃完了吗?</li>").appendTo(document.querySelector("#first"));//系统会无法执行代码,因为代码近顺序解析执行时,无法在ul.first代码之前找到该对象,但是写成回调函数的方法就可以解决这个问题<script>$(function () {$("<li>大象吃完了吗?</li>").appendTo(document.querySelector("#first"));console.log(document.querySelector("#first"));});</script>
公共代码:
<h2 class="red">用户<em style="color: green">登录</em></h2><form action="handle.php" method="post"><label for="email">Email:</label><input type="email" name="email" id="email" autofocus value="leture@php.cn" /><label for="password">Password:</label><input type="password" name="password" id="password" value="不少于6位" /><label for="confirm">记住我:</label><div><input type="radio" name="save" id="confirm" value="1" checked /><label for="confirm">保存</label><input type="radio" name="save" id="cancel" value="0" /><label for="cancel">放弃</label></div><button>登录</button></form>
演示代码:
// attr():获取/设置元素属性// attr(name):getter// attr(name,value): setterconst form = $("form);//获取表单的提交的目的地址console.log(form.attr("action"));//将表单的提交地址改为admin/check.phpform.attr("action", "admin/check.php");//setter方法的第二个参数可以传入回调函数//判断form表单的提交方式,如果是get,就跳转到query.php,如果不是,就跳转到register.phpform.attr("action", () => {let method = form.attr("method").toUpperCase();return method === "GET" ? "query.php?id=2" : "register.php";});
还是以2中的公共代码为例:
// css():设置元素的行内样式 style// css(name): getter// css(name,value): setter// css(name,callback)form.css("border-top", "6px solid green");// css(obj)form.css({"border-bottom": "6px solid blue","background-color": "lightcyan",});// 第二个参数支持回调函数,通过回调函数,每次返回一个随机数来指定对应颜色数组中的元素,并以此设置表单对象的背景颜色form.css("background-color", () => {const colors = ["pink", "lightblue", "lime", "yellow"];// 四个元素,对应的下标,索引是 0-3let i = Math.floor(Math.random() * colors.length);return colors[i];});
val(): 元素元素的值, 表单控件的value属性
如果()内传入了值,则相当于给该发展赋值
$("#email").val("admin@php.cn");//将email属性设置为admin@php.cnconsole.log($("#email").val());//控制台输出email属性值console.log($("input:password").val());console.log($("input:radio:checked").val());
// html(): innerHTML// text(): innerText / textContentconsole.log(document.querySelector("h2").innerHTML);// 获取h2标签内的html代码,输出:用户<em style="color: green">登录</em>console.log($("h2").html());// 获取h2标签内的纯文本,输出:用户登录console.log($("h2").text());
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号