Say I have the following SVG and jQuery:
<g id="test">
<rect>
<text>demo</text>
</g>
$('#test').filter('text').each(function(){
// do something
});
The filter function doesn't work with SVG, probably because jQuery was designed for DOM manipulation, not namespaced SVG.
But how can I adapt jQuery's filter function to accept SVG correctly?
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 开发者_StackOverflow中文版curLoop;
};
I don't think you need to alter the jQuery source, you can use other traversal methods that are compatible with XML.
// This works
$("#test").find("text").each(function() {
// do something
});
to keep the current element as well:
var svg = $("#test");
svg.find( "text" ).add( svg ).each(function() {
// do something
});
or:
var svg = $("#test");
svg.find( "text" ).andSelf().each(function() {
// do something
});
hope that helps. cheers!
SVG nodes work fine in jQuery selectors. The problem is that $('#test').filter('text') means "give me all nodes with id test that are also text nodes."
As keegan indicated, you're looking for the find() function, not the filter() function.
精彩评论