语法:attr(name.value)
1.设置单个属性
$('img').attr('title', '哈哈')
2.设置多个属性
$('img').attr({
alt: '呵呵',
title: '哈哈'
})
3.获取属性
let title = $('img').attr('title')
console.log(title)
4.移除属性
$('img').removeAttr('title')
4.prop() 方法
注意: 对于布尔类型的属性,不要用attr方法,应该用prop方法,prop用法和attr方法一样
<body>
<input type="button" value="选择">
<input type="button" value="不选择">
<input type="checkbox" name="" id="">
<script src="./jquery-3.4.1.js"></script>
<script>
$('input').eq(0).click(function(){
$('input').eq(2).prop('checked',true)
})
$('input').eq(1).click(function(){
$('input').eq(2).prop('checked',false)
})
</script>
</body>
案例:相册
效果:
HTML:
<div class="container">
<div class="top">
<div class="items">
<img src="./imgs/u=126814066,3359646815&fm=111&gp=0.jpg" alt="呵呵1" title="哈哈1">
</div>
<div class="items">
<img src="./imgs/u=2905076213,369041929&fm=111&gp=0.jpg" alt="呵呵2" title="哈哈2">
</div>
<div class="items">
<img src="./imgs/u=327147282,174907861&fm=11&gp=0.jpg" alt="呵呵3" title="哈哈3">
</div>
<div class="items">
<img src="./imgs/u=389138611,34558533&fm=111&gp=0.jpg" alt="呵呵4" title="哈哈4">
</div>
</div>
<div class="content"><img src="./imgs/u=126814066,3359646815&fm=111&gp=0.jpg" alt=""></div>
<div class="tips">已选中:哈哈1</div>
</div>
css:
.container {
width: 300px;
margin-left: 100px;
margin-top: 100px;
}
.top {
width: 100%;
height: 60px;
display: flex;
justify-content: space-between;
}
.items {
width: 60px;
height: 60px;
}
.items img {
width: 100%;
height: 100%;
}
.content {
width: 300px;
height: 300px;
margin-top: 20px;
}
.content img {
width: 100%;
height: 100%;
}
.tips {
margin-top: 20px;
}
js:
<script src="./jquery-3.4.1.js"></script>
<script>
$(function () {
$('.items img').click(function () {
// 获取点击图片的src路径
let src = $(this).attr('src')
// 获取点击图片的title
let title = $(this).attr('title')
// 给展示图片设置src路径
$('.content img').attr('src', src)
// 给已选中添加选中的图片的title
$('.tips').text(`已选中:${title}`)
})
})
</script>