简体   繁体   中英

How functions get evaluated in Jquery.?

My HTML,

<div id="fullcontainer">
    <div id="a">a</div>
    <div id="b">b</div>
    <div id="c">c</div>
</div>

JS,

   var cache = $('#fullcontainer').children();
   var index = cache.length - 2;
   cache.filter(':lt('+ index +')').remove();

The code that i had given above is working fine as expected, since i have cached the length in a separate variable, But the following code without caching is not working,

   var cache = $('#fullcontainer').children();
   cache.filter(':lt('+ cache.length - 2 +')').remove();

As far as i have learned the expressions at the last level should be evaluated first, But i dont know what is happening with the above piece of codes, Please advice and provide some explanations.

DEMO of the working one , Demo of the non - working one

Its will work if you enclose cache.length - 2 in brackets like,

cache.filter(':lt('+ (cache.length - 2) +')').remove();

Working Demo

Your code cache.filter(':lt('+ cache.length - 2 +')').remove(); get evaluated to

cache.filter('NaN)').remove();

it should be

cache.filter(':lt('+ (cache.length - 2) +')').remove();

You need to wrap your value in brackets ( ) to make it evaluated as number:

cache.filter(':lt('+ (cache.length - 2) +')').remove();

Updated Fiddle

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