zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    HBase 负载均衡
    HBase的写事务,MVCC及新的写线程模型
    HBase RegionServer宕机处理恢复
    分布式事务实现-Percolator
    MVC框架
    06-JS中li移动第二种形式
    05-JS中li移动第一种形式
    04-JS中文档碎片
    03-JS中添加节点
    02-JS中父节点
  • 原文地址:https://www.cnblogs.com/xinyebs/p/3317285.html
Copyright © 2011-2022 走看看