Blogger Information
Blog 18
fans 0
comment 0
visits 9776
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
第16章 4_8jQuery的DOM基本操作-作业
唐朝的博客
Original
490 people have browsed it

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1.属性与自定义属性操作:attr()和removeAttr()</title>
</head>
<body>
    <img src="./images/q2.jpg" width="200" alt="美女" title="清纯美女" id="pic" data-nation="中国">
</body>
</html>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    // 1. attr():元素属性的获取与设置
    //必须传参
    // var res = $('img').attr()

    //单参数为获取:当前属性的值
    var res = $('#pic').attr('src')

    //双参数为获取,第一个是属性名,第二个是要设置的新值
    $('#pic').attr('src', './images/q2.jpg')
    $('#pic').attr('style', 'border-radius: 50%;box-shadow:2px 6px 2px #888')


    // 由此可见,attr()是典型的集读取器与设置器二合一的方法

    //attr()可以获取到元素的自定义属性
    //html5中,可以通过data-前缀给标签添加用户自定义属性
    var res = $('#pic').attr('data-nation')

    //attr()的属性值,还支持回调函数
    $('#pic').attr('width', function(){return 100+100})
    //注意: 回调返回的数值类型,会自动转为字符类型再赋值给width属性
    var res = $('#pic').attr('width')

    //2. removeAttr():删除元素的属性
    //删除图片的内联样式属性style
    // $('#pic').removeAttr('style')
    //可以删除多个属性,多个属性之间用空格分开,返回当前元素的状态
    var res = $('#pic').removeAttr('alt title data-nation')

    //在控制台查看运行结果
    console.log(res)
</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!