我经常发现自己通过抓取模板、克隆它、将其设置为变量并使用 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/