I have figure out the index of the last p
, it does not work using $('p:lt(_index)')
. When I replace it with number, it works. Why?
$(function() { var _index = $('p:last').index(); console.log(_index); $('p:lt(_index)').css('color', 'red'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <p>1</p> <p>12</p> <p>123</p> <p>1234</p> <p>12345</p> <p>123456</p> <p>1234567</p> <p>12345678</p> <p>123456789</p> </div>
You are using the string '_index'
as argument of the :lt()
pseudo-class , not using the value of the variable. The line:
$('p:lt(_index)').css('color','red');
Should be:
$('p:lt(' + _index + ')').css('color','red');
$(function() { var _index = $('p:last').index(); console.log(_index); $('p:lt(' + _index + ')').css('color', 'red'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <p>1</p> <p>12</p> <p>123</p> <p>1234</p> <p>12345</p> <p>123456</p> <p>1234567</p> <p>12345678</p> <p>123456789</p> </div>
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.