zoukankan      html  css  js  c++  java
  • [ jquery 方法 attr(name|properties|key,value|fn) ] 此方法操作匹配的元素或元素集中的属性

    获取匹配的元素集合中的第一个元素的属性的值 | 设置每一个匹配元素的一个或多个属性:

      在jQuery 1.6中,当属性没有被设置时候,.attr()方法将返回undefined,若要检索和更改DOM属性,比如元素的checked, selected, 或 disabled状态,请使用.prop()方法

      如果第二个参数是callback,那么需要返回的是属性值,函数传参解释如下:

      1:属性名称

      2:返回属性值的函数,第一个参数为当前元素的索引值,第二个参数为原先的属性值

      注意:使用此方法来设置样式时,需要注意的就是如果直接使用obj.attr('width','100px');的格式来设置的话,那么在代码中显示的就是类似于<div width='100px'></div>这种样式,要是想设置成为我们需要的行间样式建议:

      obj.attr('style','100px;height:100px');这种样式显示正确

    实例:

    <!DOCTYPE html>
    <html lang='zh-cn'>
    <head>
    <title>Insert you title</title>
    <meta http-equiv='description' content='this is my page'>
    <meta http-equiv='keywords' content='keyword1,keyword2,keyword3'>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!-- <script type='text/javascript' src='./js/jquery-3.0.0.js'></script> -->
    <script type='text/javascript' src='./js/jquery-1.12.1.min.js'></script>
    <style type='text/css'>
        #listDemo{list-style:none;}
        #listDemo li{350px;height:20px;margin:10px 0;background:red;text-align:center;font:400 13px/20px 'Courier New';color:#FFF;}
    </style>
    <script type='text/javascript'>
        $(function(){
            $('#listDemo li').attr('width',function(index,oldAttr){
                alert(index);
            }); 
            $('#listDemo li.bar').attr('style',function(index,oldAttr){
                /*
                    只能取得处于行间的旧的属性,可能由于jquery版本等因素影响,需要注意
                */
                alert(oldAttr);
            }); 
        });
    </script>
    </head>
    <body>
       <ul id='listDemo'> 
          <li class="foo">foo</li>
          <li class="bar" style='border:1px solid #F20;'>bar</li>
          <li class="baz">baz</li>
        </ul>
    </body>
    </html>

     

  • 相关阅读:
    修改Ubuntu从文本界面登录
    Putty等工具中解决SSH连接超时断开的问题
    QoS policy-map class-map
    Linux中的do{...} while(0)
    手动增加swap分区
    __attribute__ 机制详解(一)
    欢迎来语雀关注我
    WebForm 生成并显示二维码
    《C#图解教程》 总览
    C#图解教程 第二十五章 其他主题
  • 原文地址:https://www.cnblogs.com/mysearchblog/p/5605467.html
Copyright © 2011-2022 走看看