3

我正在使用脚本使所有输入在尚不支持该功能的浏览器中具有占位符。

在我正在使用的那个脚本中

$('input[placeholder]').each(function() {

选择所有要作用的元素。

我想知道这是否会变慢,因为它不是一个非常具体的选择

$('#input').each(function() {

我知道选择方式更快(但我不想单独指定所有 id)。

您是否建议使用占位符属性向所有输入添加类,如下所示:

$('.iHaveaPlaceholder').each(function() {

使选择更快(我认为按类选择比按属性选择更快)。但这会滥用 css 类的目的,只意味着样式,它会填满 dom。

您对改进此类任务有什么建议或技巧吗?

4

4 回答 4

3

I went ahead and made a JSPerf for comparing the selectors input[placeholder], .hasPlaceholder and input with a .filter().

Now that we have some numbers to think about, lets talk about why you want to know.

When are you doing this search for 'input[placeholder]'? Hopefully only once. If you do either of these selectors in a modern browser, they will be pretty speedy (the number is operations per second....). However if you know you are only running this selectors on browsers that don't support placeholders, of the three methods listed, the .hasPlacehoder is actually the slowest in IE 6, with the custom filter winning. You want to try testing performance in the browsers that this code will actually affect..

Feel free to add your own selectors, or even better closer to your exact HTML to that page and solicit some browser testing!

Edit: I added input.hasPlaceholder to the race on a new perf...

于 2011-02-23T00:46:48.803 回答
2

除非您拥有庞大的 DOM,否则我认为性能差异不会真正发挥作用。就像您说的那样,出于“优化”的目的设置大量类会破坏文档的逻辑结构。

按类选择,不提供上下文,仍然会导致整个 DOM 被遍历。我认为按元素选择也是如此。在这里使用占位符类绝对不是答案。您想要做的是找到具有特定属性的所有输入元素 - 并且您为此目的使用了正确的选择器。

于 2011-02-22T22:22:13.003 回答
0

好吧,你可以给你的表单一个 id,然后使用$("#theForm input[placeholder]")它来减少选择器必须考虑的元素数量。

于 2011-02-22T22:18:47.250 回答
0

它并不慢(您是否测试过或只是推测?)。但如果是的话,请使用类。

于 2011-02-22T22:22:07.017 回答