本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.7节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看
还可以把传给append()的静态字符串换成函数。代码清单3-7演示了函数作为参数的使用方法,它首先会检测是否有足够的空间来添加另外的元素。
代码清单3-7 检测是否有空间来添加更多的元素
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>A function as argument for append()</title> 05 <style> 06 /* 请将下列代码移至一个外部的 07 .css 文件 */ 08 div#template { 09 display: none; 10 } 11 </style> 12 </head> 13 <body> 14 15 <div id="append-placeholder"> 16 <p>Test!</p> 17 </div> 18 19 <button id="append">Add more...</button><br> 20 21 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 22 23 <script> 24 // 请将下列代码移至一个外部的.js文件中 25 $(document).ready(function() { 26 27 $('#append').click(function() { 28 $('#append-placeholder').append(function(index, html) { 29 var more = "<p>There is room for more</p>", 30 last = "<p>This is the last one</p>", 31 spaceLeft = 160 - $.trim(html).length - last.length; 32 33 if(more.length < spaceLeft) 34 return more; 35 else if(spaceLeft > 0) 36 return last; 37 }); 38 }); 39 40 }); 41 </script> 42 </body> 43 </html>这个例子会一直添加包含文字“There is room for more”的行,直到确定没有足够的空间为止。在停止添加行之前,最后一行显示的文字是“This is the last one”。
相关资源:敏捷开发V1.0.pptx