• jquery中attr()函数三种用法


    (1)最常见的用法

         $(document).ready(function () {
    
                $('div').hover(function () {
                    //attr(),把需要设置的属性名称作为attr()的第一个参数,
                    //而将要设置的属性值作为attr()参数第二个方法。
                    $(this).attr('id', 'tmpExample');
                    $(this).text('this element Id is:' + $(this).attr('id'));
                },
                function () {
                    $(this).attr('id', '');
                    $(this).text('this element Id has been  removed');
                }
                );
            });

    (2)attr(),可以接受一个对象字面量作为参数传递给attr()

     $(document).ready(function () {
    
                $('a').hover(function () {
                    //attr(),可以接受一个对象字面量作为参数传递给attr(),在javascript中对象字面量是以“键值对”
                    //方式来定义的。{ 'id': 'tmpId', 'href': 'www.baidu.com', 'title': 'Some Tooltip Text' }
                    $(this).attr({ 'id': 'tmpId', 'href': 'www.baidu.com', 'title': 'Some Tooltip Text' });
                }, function () {
                    $(this).removeAttr('title'); //移除元素的属性,该方法接受一个属性名称作为参数
                });
            });

    (3)aattr()允许通过一个回调函数来设置属性的值。

            $(document).ready(function () {
                //attr()允许通过一个回调函数来设置属性的值。
                ///attr()为每一个li元素添加一个Id属性,通过一个回调函数来设置属性的值,
                $('li').click(function () {
                    $(this).attr('id', function () {
                        return $(this).text();
                    })
                });
    
            });

    html代码

    <form id="form1" runat="server">
            <div>
                Mouse over to change this element's id.
            </div>
            <a>A link </a>
            <ul>
                <li>Jupitere</li>
                <li>Uranus</li>
                <li>Neptune</li>
            </ul>
        </form>
  • 相关阅读:
    那些ubuntu创建用户踩过的坑
    Build tools
    version control(以git为例)讲解
    URI和URL的区别
    HTTP解析过程心得
    函数式编程(functional programming)
    cb45a_c++_STL_算法_删除_(3)_unique(唯一的意思)删除连续性的重复的数据
    cb44a_c++_STL_算法_删除_(2)remove_copy_remove_copy_if
    cb43a_c++_STL_算法_删除_(1)remove_remove_if
    cb42a_c++_STL_算法_替换_replace
  • 原文地址:https://www.cnblogs.com/xinyebs/p/3317285.html
Copyright © 2020-2023  润新知