Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在一个页面上有几个表单,我需要选择其中一个中的所有标签。有些在表单 (p, div...) 的子元素中。
做这个的最好方式是什么?
var $labels = $('#subForm label'); // want all labels at different depths var values = {}; $labels.each(function() { values[this.name] = $(this).text(); }); console.log(values);
你所拥有的 ( var $labels = $('#subForm label');) 有效。
var $labels = $('#subForm label');
但更好/更快的方法是var $labels = $('#subForm').find('label');.
var $labels = $('#subForm').find('label');
这是因为第一种方法首先搜索 DOM 中的所有标签,然后测试它们是否是具有该 id 的元素的后代,但第二种方法查找具有该 id 的元素,然后在其后代中查找标签。