《jQuery、jQuery UI及jQuery Mobile技巧与示例》——3.4 技巧:更改property和attribute...

    xiaoxiao2024-06-28  109

    本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.4节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看

    3.4 技巧:更改property和attribute

    使用attr(),可以更改HTML元素的attribute,比如rel、lang或者自定义的attribute。使用prop(),可以更改HTML元素的property。代码清单3-4演示了麻烦是怎么产生的。在某些情况下,从HTML的视角来看像是attribute,而从JavaScript的视角来看又是property。(jQuery 1.6的发布版作了修改,使得prop()函数只能用于property值,而attr()函数只能用于attribute值1。

    代码清单3-4 演示property和attribute之间的区别

    00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04  <title>Difference between prop() and attr()</title> 05  <style> 06  /* 请将下列代码移至一个外部的 07    .css文件 */ 08    09  label[other="anything"] { 10   background-color: blue; 11  } 12  13  </style> 14 </head> 15 <body> 16 17 <h2>Convert the radio buttons into check boxes and 18  change properties on the HTML</h2> 19 20 <input type="radio" name="test" id="first"> 21 <label for=first>First</label> 22 23 <input type="radio" name="test" id="second"> 24 <label for=second>Second</label> 25 26 <input type="radio" name="test" id="third"> 27 <label for=third>Third</label> 28 29 <button id="switch">Switch</button> 30 31 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 32 33 <script> 34 // 请将下列代码移至一个外部的.js文件中 35 $(document).ready(function() { 36 37  $('#switch').click(function(){ 38     39   $('input').prop('type', 'checkbox'); 40   41   $('label').attr('other', 'anything'); 42  43  }); 44  45 }); 46 </script> 47 </body> 48 </html>

    第39行使用prop()函数把单选按钮转换成了复选框。在旧版本的jQuery中,也可以使用attr()完成相同的功能。当前版本的jQuery,对这两个函数已经作了区分。

    第41行设置了一个自定义attribute。如果你的浏览器够“现代”,更改attribute后会显示第9~11行的CSS样式效果。

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)