简体   繁体   中英

string comparison find() in jquery isnt working with <

I am playing with xml on client side. below is my XML.

<ItemList>
    <Row ID="" Name="-- Select a Item --" GrpID="" Flag=""/>
    <Row ID="S5"  Name="Item 1" GrpID="G7" Flag="0"/>
    <Row ID="S6"  Name="Item 2" GrpID="G7" Flag="0"/>
    <Row ID="S7"  Name="Item 3" GrpID="G7" Flag="0"/>
    <Row ID="S85" Name="Item 4" GrpID="G7" Flag="0"/>
    <Row ID="S5"  Name="Item 11" GrpID="G4" Flag="0"/>
    <Row ID="S13" Name="Item 5" GrpID="G7" Flag="0"/>
    <Row ID="S14" Name="Item 6" GrpID="G7" Flag="0"/>
    <Row ID="S15" Name="Item 7" GrpID="G7" Flag="0"/>
    <Row ID="S16" Name="Item 8" GrpID="G7" Flag="0"/>
    <Row ID="S17" Name="Item 9" GrpID="G7" Flag="0"/>
    <Row ID="S12" Name="Item 12" GrpID="G4" Flag="0"/>
    <Row ID="S22" Name="Item 22" GrpID="" Flag="0"/>
    <Row ID="S25" Name="Item 26" GrpID="" Flag="0"/>
</ItemList>

I have to assign items with (GrpID=G7 and ID<'S5') OR (GrpID is '')

$(xmlItems).find("Row[GrpID='7'][ID<'S82'],[GrpID='']")

Where am I doing wrong. I could get with the below.

$(xmlItems).find("Row[GrpID='7'][ID='S85'],[GrpID='']")

the problem "=" is working and "<" is not working for Item ID (strings) comparison.

Jquery uses CSS selectors; the syntax does not support matching with < or > . You need to do this using the jQuery.filter() , for example:

$filtered = $(xmlItems).find("Row[GrpID='G7']").filter(
    function (index, element) {
        return element.ID < 'S5';
    }
);

However notice that the string comparison still might not do what you mean - this is not a numeric comparison and 'S11' < 'S2' is true.

The return statement in @AnttiHaapala should be adjusted slightly for the code to work. Please see the modified version below:

$filtered = $(xmlItems).find("Row[GrpID='G7']").filter(
    function (index, element) {
        return $(element).attr('ID') < 'S5';
    }
)
.add( $(xmlItems).find( 'row[GrpID=""]' ) );

This is because ID is an attribute of row . Since element is an iterator for row , you want to grab it's ID attribute like this:

$(element).attr( 'ID' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM