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>

 

 

 

 

 

posted @ 2013-09-12 16:51  xinyebs  阅读(1734)  评论(0编辑  收藏  举报