4.2 Your arrays on steroids

优质
小牛编辑
130浏览
2023-12-01

就如我们上面提到的,把你的Array中的elements当成相同的类型使用相同的属性和函数是很通用(Common,不知该翻译成通用还是庸俗)的。让我们看看怎么样利用我们新的马力强劲的Arrays的迭代功能吧。 依照标准找到一个element。

<script> function findEmployeeById(emp_id){ var listBox = $('lstEmployees') var options = listBox.getElementsByTagName('option'); options = $A(options); var opt = options.find( function(employee){ return (employee.value == emp_id); }); alert(opt.innerHTML); //displays the employee name } </script> <select id="lstEmployees" size="10" > <option value="5">Buchanan, Steven</option> <option value="8">Callahan, Laura</option> <option value="1">Davolio, Nancy</option> </select> <input type="button" value="Find Laura" onclick="findEmployeeById(8);" >

现在我们再下一城,看看如何过滤一个Array中的元素,从每个元素中得到我们想要的成员。

<script> function showLocalLinks(paragraph){ paragraph = $(paragraph); var links = $A(paragraph.getElementsByTagName('a')); //find links that do not start with 'http' var localLinks = links.findAll( function(link){ var start = link.href.substring(0,4); return start !='http'; }); //now the link texts var texts = localLinks.pluck('innerHTML'); //get them in a single string var result = texts.inspect(); alert(result); } </script> <p id="someText"> This <a href="http://othersite.com/page.html">text</a> has a <a href="#localAnchor">lot</a> of <a href="#otherAnchor">links</a>. Some are <a href="http://wherever.com/page.html">external</a> and some are <a href="#someAnchor">local</a> </p> <input type=button value="Find Local Links" onclick="showLocalLinks('someText')">

上面的代码仅仅是一点小小的实践让人爱上这种语法。请参看 Enumerable和Array的所有函数