批改状态:合格
老师批语:dom操作很重要的呀
jquery操作dom元素属性的方法有 , attr()和prop(); 只有一个参数时,它们都能够获取当前属性的值,有两个参数时,设置前一个参数属性值为后一个参数. 它们的区别是操作HTML元素本身就带有的固有属性,在处理时,使用prop()方法。自己自定义的DOM属性,在处理时,使用attr()方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>attr和prop</title>
<style>
.box>div{ height: 80px; margin-bottom: 15px;}
</style>
<script src="https://www.php.cn/static/blogs/js/jquery3.4.1.js"></script>
<script>
function _get(obj){
var flag = $(obj).attr('flag');
//flag 为自定义属性,可以用attr()方法获取到
var flag2 = $(obj).prop('flag');
//flag 为自定义属性,prop()方法
var className = $(obj).prop('class');
var className2 = $(obj).attr('class');
alert(flag);
alert(flag2); //返回的是undefind
alert(className); //class为html固有属性,prop()方法获取到
alert(className2); //class为html固有属性,attr()方法获取到
}
function _change(obj){
$(obj).attr('data','attr和prop');
//data为自定义属性,attr方法可以设置
$(obj).prop('data','attr和prop');
//data为自定义属性,prop方法不可以设置
}
function _check(){
// 用户手动勾选复选框后
$('input[type=checkbox]').prop('checked',false);
//复选框勾选后,prop()方法可以取消掉勾选
$('input[type=checkbox]').attr('checked',false);
//attr()方法不能取消勾选
}
</script>
</head>
<body>
<div class="box">
<div class="box1" flag="橙色" style="background:#f60;" onclick="_get(this); _change(this)"></div>
<div class="box2" flag="灰色" style="background:#999;" onclick="_get(this); _change(this)"></div>
<div><input type="checkbox">复选框 不存在checked</div>
<div><input type="checkbox" checked>复选框 存在checked</div>
<button onclick="_check()">取消复选框</button>
</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例

setInterval()和clearInterval()定时器循环
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style>
.box{ width: 300px; margin:50px auto; }
.time{ width: 80px; height: 80px; border-radius: 50%; border:1px solid red; margin-bottom: 30px; line-height: 80px; text-align: center; font-size: 24px}
</style>
<script src="https://www.php.cn/static/blogs/js/jquery3.4.1.js"></script>
<script>
var i;
var key = true;
function setTime(i){
var time = setInterval(function(){
$('.time').text(i)
i--;
if (i<0 || key) {
//清除循环
clearInterval(time);
}
},1000)
}
function start(){
i = $('.time').text();
if (key) {
key = false;
setTime(i);
}else{
key = true;
$('.time').text(i)
}
}
</script>
</head>
<body>
<div class="box">
<div class="time">10</div>
<button onclick="start()">开始/暂停</button>
</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例

prop()函数的结果:
1.如果有相应的属性,返回指定属性值。
2.如果没有相应的属性,返回值是空字符串。
attr()函数的结果:
1.如果有相应的属性,返回指定属性值。
2.如果没有相应的属性,返回值是undefined。
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop()
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号