jquery - 有没有更好的方法使用 jQuery 按类查找单个元素?

标签 jquery performance

我经常发现自己通过抓取模板、克隆它、将其设置为变量并使用 find('.class') 查找其下的元素,然后为它们分配唯一的 id 和否则,在将列表项附加到我正在执行的任何列表之前与它们一起工作。

例如,如果我有一个项目列表,所有这些项目都是从模板设置的,并且包括由类指定的子项目,我会这样做(未经测试,只是一个过程示例):

// Create my list item.
$ListItem = $('#list_item_template').clone();

// Set the id for the first field so I can work with it directly later.
$ListItem.find('.field_one).attr('id', 'field_one_'+ListItemID).val('field one value for this list item');

// Set the id for the second field so I can work with it directly later.
$ListItem.find('.field_two).attr('id', 'field_two_'+ListItemID).val('field two value for this list item');

// Add the item to the list
$ListItem.appendTo($List);

现在,我可以访问第 X 个列表项的第一个“字段”,例如 $('#field_one_[ListItemID]。

问题是,即使我指定了 $ListItem,我也知道当我使用 find('.field_one') 查找要添加 id 的字段时,它会遍历模板中的每个元素来查找该类。这对性能影响不大,但如果它是一个很长的列表或一个很长的模板,它就会增加。

有更有效的方法吗?就像您期望从名为 .findOnce() 的函数中得到的东西一样?

谢谢!

最佳答案

这取决于你的 DOM 是如何设置的。 children()find() 快,例如,就像 parent()parents() 快.

示例:$ListItem.children('.field_one')

关于jquery - 有没有更好的方法使用 jQuery 按类查找单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6880420/

相关文章:

带有scrollTo插件的jQuery DataTables自动看到div

jquery - 使用 jQuery 在父容器中查找元素

regex - 在 bash 中 Grepping 一个 20g 的文件

java - 我如何评估哈希表的实现? (引用HashMap)

javascript - 为什么在 Nginx 中增加 worker_connections 会使应用程序在 node.js 集群中变慢?

jquery - 我正在构建的 Wordpress 页面正在使我的 iPhone 崩溃

javascript - 单击另一个按钮时,一个按钮将被禁用

mysql - WHERE 与 HAVING 具有多个 IF/LIKE 的计算字段

c - 出于性能原因将代码推送到内核或用户空间?

javascript - jQuery 元素值等于 x