jQuery操作属性

语法: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方法一样
来自jQuery官网

<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>

前端进阶精选:点此去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值