如何让jQuery的’filter’function正常运行SVG节点?

说我有以下SVG和jQuery:

  demo  $('#test').filter('text').each(function(){ // do something }); 

filterfunction不适用于SVG,可能是因为jQuery是为DOM操作设计的,而不是命名空间的SVG。

但是如何才能使jQuery的filterfunction正确地接受SVG呢?

 Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; 

我认为你不需要改变jQuery源代码,你可以使用与XML兼容的其他遍历方法。

 // This works $("#test").find("text").each(function() { // do something }); 

保持当前元素:

 var svg = $("#test"); svg.find( "text" ).add( svg ).each(function() { // do something }); 

要么:

 var svg = $("#test"); svg.find( "text" ).andSelf().each(function() { // do something }); 

希望有所帮助。 干杯!

SVG节点在jQuery选择器中工作正常。 问题是$(’#test’)。filter(’text’)意味着“给我所有节点都有id 测试 ,也是文本节点。”

正如keegan指出的那样,你正在寻找find()函数,而不是filter()函数。