1

在我正在开发的应用程序中,我使用原型的 $$ 函数来获取页面上的所有 A HREF 元素并通过 javascript 更改它们的链接。只要页面上有合理数量的链接,它就可以正常工作。

在一些罕见的用例中,$$ 函数返回 5K+ 次点击(太棒了:))有没有办法优化它的行为,或者完全摆脱它以获得更高的性能?

编辑——评论中的重要细节

具体代码为:

$$('a:not([href="#"])').each(function(item){});

我正在使用prototypejs 1.7.1

4

2 回答 2

2

如果您的选择器有点慢,那可能:not()就是这样做的。<a>您可以从所有元素的列表开始过滤掉具有显式代码的那些:

var anchors = $$('a').reject(function(a) { return a.href === '#'; });

(我的原型已经很生锈了 :) 这适用于任何使用 Sizzle 的现代库。那些伪选择器运算符:not效率不高;当情况不涉及大规模因素时,它们作为速记很有用,但在像你这样的情况下不是一个好主意。查找<a>文档中的所有元素非常快,然后遍历该列表也应该非常快。

于 2013-08-01T15:00:14.207 回答
2

你可以用完全不同的方式来解决这个问题。

例如,您有一个包含 5000 条记录的表

<table id="recordtable">
<tr>
    <td>Record 1</td>
    <td><a href="#link1">click here</a></td>
</tr>
......//snip
<tr>
    <td>Record 100</td>
    <td><a href="#link100">click here</a></td>
</tr>
.......//snip
</table>

现在在桌子上放一个观察者来观察链接的点击

$('recordtable').on('click','a:not([href="#"])',function(e){
    //FYI 'this' points to the table element
    //e is the event object passed in-------------------^^^
    //use e.findElement() to get the element that the click originated on
    var el = e.findElement();
    if(el.readAttribute('href') != "something")
    {
        window.location.href = 'some other link';
    }
    //most importantly stop the event so that the link doesn't fire
    e.stop();
});
于 2013-08-01T15:00:17.473 回答