0

有没有办法将:($("#first").find("input").not("td td input") http://jsfiddle.net/4K9TG/ ...转换为 querySelectorAll 选择器?

(从jQuery 继续:find() children 直到遇到某个阈值元素

4

2 回答 2

1

not只是对满足条件的集合的过滤器。看看这是否有帮助。

var query = function(selector, element) {
  element = element || document;
  return [].slice.call(element.querySelectorAll(selector));
};

var not = function(selector) {
  var exclude = query(selector);
  return function(element) {
    return exclude.indexOf(element) == -1;
  };
};

var inputs = query('#first input').filter(not('td td input'));

这是一个演示:http: //jsbin.com/EJAyiSux/1/edit

您可以将大多数 jQuery 方法实现为简单的filtermap具有高阶函数的序列,如上所示。毕竟,jQuery 集合只是元素的数组。

于 2013-12-16T09:02:13.920 回答
0

我最终做了一个函数来做到这一点。

http://jsfiddle.net/4K9TG/2/

var n = get_elements_until (document.getElementById('first'), 'input', 'td')
console.log (n)

function get_elements_until (parent, tagname_to_search_for, tagname_to_stop_at) {
 var element_list = []
 var stack_current = [parent]
 while (true) {
 var stack_new = []
  for (var s = 0, curlen_s = stack_current.length; s < curlen_s; s++) {
   var children = stack_current[s].childNodes
   for (var i = 0, curlen = children.length; i < curlen; i++) {
    var child = children[i], tagname = child.tagName
    if (typeof tagname == "undefined") continue
    tagname = tagname.toLowerCase ()
    if (tagname == tagname_to_search_for) element_list.push (child)
    if (tagname != tagname_to_stop_at) stack_new.push (child)
   }
  }
  stack_current = stack_new
  if (stack_new.length == 0) break
 }
 return element_list
}
于 2013-12-17T03:35:57.463 回答